import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  SafeAreaView,
  Platform,
} from 'react-native';
import { useRouter } from 'expo-router';
import { API_URL } from '../../config';
import { useCustomerId } from '../../hooks/useCustomerId';
import { useTableStatus } from '../../hooks/useTableStatus';
import MaintenanceModal from '../../components/MaintenanceModal';
import StaffOperationModal from '../../components/StaffOperationModal';
import { useTranslation } from '../../hooks/useTranslation';

interface BillingInfo {
  totalOrders: number;
  pendingOrders: number;
  firstOrderTime: string | null;
  subtotal: number;
  taxAmount: number;
  totalAmount: number;
}

export default function BillingScreen() {
  const router = useRouter();
  const { customerId, refreshCustomerId } = useCustomerId();
  const { tableNumber, setTableNumber, locked } = useTableStatus();
  const [billingInfo, setBillingInfo] = useState<BillingInfo | null>(null);
  const { t } = useTranslation();
  
  // 顧客IDが取得できている場合（入店処理完了）は、locked状態に関係なく画面を表示
  const shouldShowStaffOperationModal = locked && !customerId;
  const [loading, setLoading] = useState(true);
  const [showMaintenanceModal, setShowMaintenanceModal] = useState(false);

  // 会計情報を取得
  useEffect(() => {
    const fetchBillingInfo = async () => {
      if (!customerId) {
        setBillingInfo(null);
        setLoading(false);
        return;
      }

      try {
        const response = await fetch(`${API_URL}/customers/billing`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ customer_id: customerId }),
        });

        if (response.ok) {
          const data = await response.json();
          setBillingInfo(data);
        } else {
          const errorText = await response.text();
          console.error('会計情報取得エラー:', response.status, errorText);
          setBillingInfo(null);
        }
      } catch (error) {
        console.error('会計情報取得エラー:', error);
        setBillingInfo(null);
      } finally {
        setLoading(false);
      }
    };

    fetchBillingInfo();
  }, [customerId]);

  // 顧客IDが自動設定された場合の処理
  useEffect(() => {
    if (customerId) {
      // 顧客IDが設定された場合の処理
    }
  }, [customerId]);

  const handleCheckout = () => {
    Alert.alert(
      t('billingConfirmTitle'),
      t('billingConfirmMessage'),
      [
        {
          text: 'キャンセル',
          style: 'cancel',
        },
        {
          text: t('billingComplete'),
          onPress: () => {
            // 会計完了処理（実装予定）
            Alert.alert(t('billingComplete'), t('billingCompleteThanks'));
          },
        },
      ]
    );
  };

  const handleLogout = () => {
    // プラットフォームに応じて確認ダイアログを選択
    if (Platform.OS === 'web') {
      // Webプラットフォーム用の確認ダイアログ
      if (confirm('利用を停止しますか？追加注文ができなくなります。')) {
        performLogout();
      }
    } else {
      // モバイルプラットフォーム用のAlert
      Alert.alert(
        '利用停止確認',
        '利用を停止しますか？追加注文ができなくなります。',
        [
          {
            text: 'キャンセル',
            style: 'cancel',
          },
          {
            text: '利用停止',
            style: 'destructive',
            onPress: performLogout,
          },
        ]
      );
    }
  };

  const performLogout = async () => {
    try {
      // セッションをクリア
      const tableResponse = await fetch(`${API_URL}/session/table`, {
        method: 'DELETE',
        credentials: 'include',
        headers: {
          'X-App-Type': 'front'
        }
      });
      
      
      const customerResponse = await fetch(`${API_URL}/session/customer-id`, {
        method: 'DELETE',
        credentials: 'include',
        headers: {
          'X-App-Type': 'front'
        }
      });


      // テーブル番号をクリア
      setTableNumber('');
      
      // メイン画面に戻る
      router.replace('/(tabs)');
      
      // プラットフォームに応じて完了メッセージを選択
      if (Platform.OS === 'web') {
        alert('利用を停止しました。');
      } else {
        Alert.alert('利用停止完了', '利用を停止しました。');
      }
    } catch (error) {
      console.error('利用停止エラー:', error);
      if (Platform.OS === 'web') {
        alert('利用停止処理に失敗しました。');
      } else {
        Alert.alert('エラー', '利用停止処理に失敗しました。');
      }
    }
  };

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{t('billing')}</Text>
        </View>
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>{t('loading')}</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (!customerId || !billingInfo) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{t('billing')}</Text>
        </View>
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>{t('billingEmpty')}</Text>
          <Text style={styles.emptySubtext}>
            {t('billingEmptyDescription')}
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>{t('billing')}</Text>
        <Text style={styles.tableNumber}>{tableNumber}</Text>
      </View>

      <ScrollView style={styles.content}>
        <View style={styles.billingCard}>
          <Text style={styles.sectionTitle}>{t('billingInfo')}</Text>
          
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>{t('totalOrders')}</Text>
            <Text style={styles.infoValue}>{billingInfo.totalOrders}件</Text>
          </View>
          
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>{t('pendingOrders')}</Text>
            <Text style={styles.infoValue}>{billingInfo.pendingOrders}件</Text>
          </View>

          {billingInfo.firstOrderTime && (
            <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>{t('startTime')}</Text>
              <Text style={styles.infoValue}>
                {new Date(billingInfo.firstOrderTime).toLocaleTimeString('ja-JP', {
                  hour: '2-digit',
                  minute: '2-digit'
                })}
              </Text>
            </View>
          )}

          <View style={styles.divider} />

          <View style={styles.summarySection}>
            <View style={styles.summaryRow}>
          <Text style={styles.summaryLabel}>{t('subtotal')}</Text>
              <Text style={styles.summaryValue}>¥{Number(billingInfo.subtotal).toLocaleString()}</Text>
            </View>
            <View style={styles.summaryRow}>
          <Text style={styles.summaryLabel}>{t('tax')}</Text>
              <Text style={styles.summaryValue}>¥{Number(billingInfo.taxAmount).toLocaleString()}</Text>
            </View>
            <View style={styles.summaryRow}>
          <Text style={styles.totalLabel}>{t('total')}</Text>
              <Text style={styles.totalValue}>¥{Number(billingInfo.totalAmount).toLocaleString()}</Text>
            </View>
          </View>
        </View>

        <TouchableOpacity 
          style={styles.checkoutButton}
          onPress={handleCheckout}
        >
          <Text style={styles.checkoutButtonText}>{t('billingCompleteButton')}</Text>
        </TouchableOpacity>

        <TouchableOpacity 
          style={styles.logoutButton}
          onPress={handleLogout}
          activeOpacity={0.7}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Text style={styles.logoutButtonText}>利用停止</Text>
        </TouchableOpacity>
      </ScrollView>

      <MaintenanceModal
        visible={showMaintenanceModal}
        onClose={() => setShowMaintenanceModal(false)}
        currentTableNumber={tableNumber}
        onTableChange={setTableNumber}
      />

      {shouldShowStaffOperationModal && <StaffOperationModal visible={true} isWaitingForCheckIn={true} />}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9FAFB',
  },
  header: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#111827',
  },
  tableNumber: {
    fontSize: 14,
    color: '#6B7280',
    marginTop: 4,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 16,
    color: '#6B7280',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 40,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    color: '#374151',
    marginBottom: 8,
  },
  emptySubtext: {
    fontSize: 14,
    color: '#6B7280',
    textAlign: 'center',
    lineHeight: 20,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  billingCard: {
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    padding: 20,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
    marginBottom: 16,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
  },
  infoLabel: {
    fontSize: 16,
    color: '#6B7280',
  },
  infoValue: {
    fontSize: 16,
    fontWeight: '600',
    color: '#111827',
  },
  divider: {
    height: 1,
    backgroundColor: '#E5E7EB',
    marginVertical: 16,
  },
  summarySection: {
    marginTop: 8,
  },
  summaryRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 4,
  },
  summaryLabel: {
    fontSize: 16,
    color: '#6B7280',
  },
  summaryValue: {
    fontSize: 16,
    fontWeight: '600',
    color: '#111827',
  },
  totalLabel: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
  },
  totalValue: {
    fontSize: 20,
    fontWeight: '700',
    color: '#F97316',
  },
  checkoutButton: {
    backgroundColor: '#3B82F6',
    paddingVertical: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 20,
  },
  checkoutButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  logoutButton: {
    backgroundColor: '#EF4444',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 8,
    alignItems: 'center',
    alignSelf: 'center',
    marginBottom: 20,
    minHeight: 44, // タップしやすい最小高さ
  },
  logoutButtonText: {
    color: '#FFFFFF',
    fontSize: 12,
    fontWeight: '500',
  },
});
