import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { API_URL } from '../../../../config';

interface TableValidationResponse {
  valid: boolean;
  table?: {
    id: number;
    name: string;
    storeId: number;
    status: string;
  };
  store?: {
    id: number;
    name: string;
  };
  message?: string;
}

export default function TableValidationScreen() {
  const params = useLocalSearchParams<{ storeId?: string | string[]; tableId?: string | string[] }>();
  const storeIdParam = Array.isArray(params.storeId) ? params.storeId[0] : params.storeId;
  const tableIdParam = Array.isArray(params.tableId) ? params.tableId[0] : params.tableId;
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [validationResult, setValidationResult] = useState<TableValidationResponse | null>(null);

  useEffect(() => {
    if (!storeIdParam || !tableIdParam) {
      setValidationResult({
        valid: false,
        message: 'URLに店舗またはテーブルの情報が不足しています。'
      });
      setLoading(false);
      return;
    }

    validateTable(storeIdParam, tableIdParam);
  }, [storeIdParam, tableIdParam]);

  const validateTable = async (storeIdValue: string, tableIdValue: string) => {
    try {
      setLoading(true);

      const parsedStoreId = Number.parseInt(storeIdValue, 10);
      const parsedTableId = Number.parseInt(tableIdValue, 10);

      if (Number.isNaN(parsedStoreId) || Number.isNaN(parsedTableId)) {
        setValidationResult({
          valid: false,
          message: 'テーブルの指定が正しくありません。'
        });
        return;
      }

      const response = await fetch(`${API_URL}/tables/validate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-App-Type': 'front'
        },
        body: JSON.stringify({
          store_id: parsedStoreId,
          table_id: parsedTableId
        })
      });

      const result = await response.json();

      if (response.ok && result.valid) {
        // テーブルが有効な場合、メイン画面にリダイレクト
        // セッションにテーブル情報を保存
        const sessionResponse = await fetch(`${API_URL}/session/table`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'X-App-Type': 'front'
          },
          body: JSON.stringify({ 
            tableNumber: result.table?.name,
            storeId: result.store?.id
          }),
        });


        // メイン画面にリダイレクト（URLパラメータを保持）
        router.replace({
          pathname: '/(tabs)',
          params: {
            storeId: storeIdValue,
            tableId: tableIdValue
          }
        });
      } else {
        setValidationResult(result);
      }
    } catch (error) {
      console.error('テーブル検証エラー:', error);
      setValidationResult({
        valid: false,
        message: 'テーブルの検証に失敗しました。'
      });
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#3B82F6" />
        <Text style={{ marginTop: 16, fontSize: 16, color: '#6B7280' }}>
          テーブルを検証中...
        </Text>
      </View>
    );
  }

  if (!validationResult?.valid) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
        <Text style={{ fontSize: 24, fontWeight: 'bold', color: '#EF4444', marginBottom: 16 }}>
          エラー
        </Text>
        <Text style={{ fontSize: 16, color: '#6B7280', textAlign: 'center', marginBottom: 24 }}>
          {validationResult?.message || '無効なテーブルです。'}
        </Text>
        <Text style={{ fontSize: 14, color: '#9CA3AF', textAlign: 'center' }}>
          店舗スタッフにお問い合わせください。
        </Text>
      </View>
    );
  }

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ fontSize: 16, color: '#6B7280' }}>
        リダイレクト中...
      </Text>
    </View>
  );
}
