'use client';

export const dynamic = 'force-dynamic';

import { useForm, useFieldArray } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { useAuthStore } from '@/lib/auth-store';
import { apiClient } from '@/lib/api-client';
import { useState, useEffect } from 'react';
import { CheckCircle, ExternalLink, Loader2 } from 'lucide-react';

const passengerSchema = z.object({
  name: z.string().min(2, 'Name is required'),
  dateOfBirth: z.string().min(1, 'Date of birth is required'),
  gender: z.enum(['Male', 'Female']).optional(),
  nationality: z.string().min(1, 'Nationality is required'),
  phone: z.string().optional(),
  email: z.string().email('Invalid email').optional().or(z.literal('')),
  nationalId: z.string().optional(),
  passportNumber: z.string().optional(),
  passportCountry: z.string().optional(),
  passportIssueDate: z.string().optional(),
  passportExpiryDate: z.string().optional(),
  passportIssuingAuthority: z.string().optional(),
  faydaVerified: z.boolean().optional(),
  faydaSub: z.string().optional(),
  formExpanded: z.boolean().optional(),
}).refine((data) => {
  // For non-Ethiopian passengers, passport number and country are required
  if (data.nationality !== 'ETHIOPIAN' && data.nationality !== 'Ethiopian') {
    return data.passportNumber && data.passportNumber.length > 0 && 
           data.passportCountry && data.passportCountry.length > 0;
  }
  return true;
}, {
  message: 'Passport number and country are required for non-Ethiopian passengers',
  path: ['passportNumber'],
});

const formSchema = z.object({
  passengers: z.array(passengerSchema),
  createAccount: z.boolean(),
});

type FormData = z.infer<typeof formSchema>;

export default function PassengersPage() {
  const router = useRouter();
  const { searchCriteria, setPassengers, setCreateAccount } = useBookingStore();
  const { user, isAuthenticated, updateUser } = useAuthStore();
  const [faydaEnabled, setFaydaEnabled] = useState(true);
  const [verificationStatus, setVerificationStatus] = useState<Record<number, 'success' | 'error'>>({});
  const [updatingUser, setUpdatingUser] = useState(false);
  const [saving, setSaving] = useState(false);

  const totalPassengers = (searchCriteria?.adultCount || 1) + (searchCriteria?.childCount || 0);

  const { register, control, handleSubmit, setValue, watch, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      passengers: Array.from({ length: totalPassengers }, () => ({
        name: '',
        dateOfBirth: '',
        gender: undefined,
        nationality: searchCriteria?.nationality || 'ETHIOPIAN',
        phone: '',
        email: '',
        nationalId: '',
        passportNumber: '',
        passportCountry: '',
        passportIssueDate: '',
        passportExpiryDate: '',
        passportIssuingAuthority: '',
        faydaVerified: false,
        formExpanded: false,
      })),
      createAccount: false,
    },
  });

  const { fields } = useFieldArray({ control, name: 'passengers' });
  const passengers = watch('passengers');

  useEffect(() => {
    const checkFaydaStatus = async () => {
      try {
        const response: any = await apiClient.get('/config/fayda-status');
        setFaydaEnabled(response?.enabled ?? true);
      } catch {
        setFaydaEnabled(true);
      }
    };
    checkFaydaStatus();

    if (isAuthenticated && user && searchCriteria?.nationality === 'ETHIOPIAN') {
      if (user.faydaVerified && user.fullName && user.dateOfBirth) {
        setValue('passengers.0.name', user.fullName);
        setValue('passengers.0.dateOfBirth', user.dateOfBirth);
        setValue('passengers.0.gender', user.gender as any);
        setValue('passengers.0.nationality', user.nationality || 'ETHIOPIAN');
        setValue('passengers.0.phone', user.phone || '');
        setValue('passengers.0.email', user.email || '');
        setValue('passengers.0.faydaVerified', true);
        setValue('passengers.0.faydaSub', user.faydaSub || '');
        setValue('passengers.0.formExpanded', true);
        setVerificationStatus({ 0: 'success' });
      }
    }
  }, [isAuthenticated, user, searchCriteria, setValue]);

  const openFaydaVerification = async (index: number) => {
    if (typeof window === 'undefined') return; // Guard for SSR
    
    const faydaUrl = process.env.NEXT_PUBLIC_FAYDA_URL || 'https://fayda.gov.et/verify';
    const callbackUrl = `${window.location.origin}/booking/passengers?faydaCallback=${index}`;
    const width = 600;
    const height = 700;
    const left = (window.screen.width - width) / 2;
    const top = (window.screen.height - height) / 2;
    
    window.open(
      `${faydaUrl}?callback=${encodeURIComponent(callbackUrl)}`,
      'FaydaVerification',
      `width=${width},height=${height},left=${left},top=${top},scrollbars=yes,resizable=yes`
    );

    const handleMessage = async (event: MessageEvent) => {
      if (event.data?.type === 'FAYDA_VERIFIED' && event.data?.index === index) {
        const data = event.data.passengerData;
        setValue(`passengers.${index}.name`, data.fullName);
        setValue(`passengers.${index}.dateOfBirth`, data.dateOfBirth.split('T')[0]);
        setValue(`passengers.${index}.gender`, data.gender);
        setValue(`passengers.${index}.nationality`, data.nationality || 'ETHIOPIAN');
        setValue(`passengers.${index}.phone`, data.phone || '');
        setValue(`passengers.${index}.email`, data.email || '');
        setValue(`passengers.${index}.faydaVerified`, true);
        setValue(`passengers.${index}.faydaSub`, data.faydaSub);
        setValue(`passengers.${index}.formExpanded`, true);
        setVerificationStatus({ ...verificationStatus, [index]: 'success' });

        if (index === 0 && isAuthenticated && user) {
          setUpdatingUser(true);
          try {
            await apiClient.patch('/auth/profile', {
              fullName: data.fullName,
              dateOfBirth: data.dateOfBirth,
              gender: data.gender,
              nationality: data.nationality || 'ETHIOPIAN',
              phone: data.phone,
              faydaVerified: true,
              faydaSub: data.faydaSub,
            });
            updateUser({
              fullName: data.fullName,
              dateOfBirth: data.dateOfBirth.split('T')[0],
              gender: data.gender,
              nationality: data.nationality || 'ETHIOPIAN',
              phone: data.phone,
              faydaVerified: true,
              faydaSub: data.faydaSub,
            });
          } catch (error) {
            console.error('Failed to update user profile:', error);
          } finally {
            setUpdatingUser(false);
          }
        }

        window.removeEventListener('message', handleMessage);
      }
    };
    
    window.addEventListener('message', handleMessage);
  };

  const toggleForm = (index: number) => {
    setValue(`passengers.${index}.formExpanded`, !passengers[index].formExpanded);
  };

  const onSubmit = async (data: FormData) => {
    setSaving(true);
    try {
      const passengerDetails = data.passengers.map((p, i) => ({
        ...p,
        isPrimaryPassenger: i === 0,
      }));

      // Save passenger details to database before proceeding
      const deviceId = typeof window !== 'undefined' 
        ? (localStorage.getItem('deviceId') || crypto.randomUUID())
        : crypto.randomUUID();
      
      await apiClient.post('/passengers/save-details', {
        passengers: passengerDetails,
        userId: user?.id,
        deviceId,
      });
      
      setPassengers(passengerDetails);
      setCreateAccount(data.createAccount);
      router.push('/booking/seats');
    } catch (error) {
      console.error('Failed to save passenger details:', error);
      alert('Failed to save passenger details. Please try again.');
    } finally {
      setSaving(false);
    }
  };

  if (!searchCriteria) {
    router.push('/booking/search');
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-4xl mx-auto">
          <h1 className="text-3xl font-bold mb-6 text-gray-900 dark:text-gray-100">Passenger Details</h1>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {fields.map((field, index) => {
              const isEthiopian = passengers[index]?.nationality === 'ETHIOPIAN';
              const isFormExpanded = passengers[index]?.formExpanded;
              const status = verificationStatus[index];
              const isPrimaryPassenger = index === 0;
              const isLoggedInAndVerified = isPrimaryPassenger && isAuthenticated && user?.faydaVerified;
              const isLoggedInNotVerified = isPrimaryPassenger && isAuthenticated && !user?.faydaVerified;
              const showVerifyButton = isEthiopian && faydaEnabled && !isFormExpanded && !isLoggedInAndVerified;
              const showManualEntryLink = isEthiopian && !faydaEnabled && !isFormExpanded;

              return (
                <div key={field.id} className="card">
                  <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
                    Passenger {index + 1} {index === 0 && '(Primary)'}
                    {index < (searchCriteria.adultCount || 1) ? ' - Adult' : ' - Child'}
                    <span className="ml-2 text-sm font-normal text-gray-600 dark:text-gray-400">
                      ({isEthiopian ? 'Ethiopian' : searchCriteria.nationality === 'DJIBOUTIAN' ? 'Djiboutian' : 'International'})
                    </span>
                  </h3>

                  {showVerifyButton ? (
                    <div className="text-center py-8">
                      {isLoggedInNotVerified && (
                        <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg">
                          <p className="text-sm text-blue-700 dark:text-blue-300">
                            Please verify your identity with Fayda to complete your profile
                          </p>
                        </div>
                      )}
                      <button
                        type="button"
                        onClick={() => openFaydaVerification(index)}
                        className="btn-primary flex items-center justify-center gap-2 mx-auto"
                        disabled={updatingUser}
                      >
                        {updatingUser ? (
                          <Loader2 className="w-5 h-5 animate-spin" />
                        ) : (
                          <ExternalLink className="w-5 h-5" />
                        )}
                        {updatingUser ? 'Updating Profile...' : 'Verify with Fayda'}
                      </button>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-3">
                        Click to verify your Ethiopian national ID
                      </p>
                      {!isLoggedInNotVerified && (
                        <button
                          type="button"
                          onClick={() => toggleForm(index)}
                          className="text-sm text-primary hover:underline mt-2"
                        >
                          Or enter details manually
                        </button>
                      )}
                    </div>
                  ) : showManualEntryLink ? (
                    <div className="text-center py-8">
                      <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                        Fayda verification is currently unavailable
                      </p>
                      <button
                        type="button"
                        onClick={() => toggleForm(index)}
                        className="btn-primary"
                      >
                        Enter Details Manually
                      </button>
                    </div>
                  ) : (
                  <div className="space-y-4">
                    {isEthiopian ? (
                      <>
                        {status === 'success' && (
                          <div className="p-3 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-lg mb-4">
                            <p className="text-green-700 dark:text-green-300 text-sm flex items-center gap-2">
                              <CheckCircle className="w-4 h-4" /> Verified with Fayda
                            </p>
                          </div>
                        )}

                        <div className="grid md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Full Name *</label>
                            <input
                              {...register(`passengers.${index}.name`)}
                              className="input-field"
                              placeholder="Full name as per ID"
                            />
                            {errors.passengers?.[index]?.name && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.name?.message}</p>
                            )}
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Date of Birth *</label>
                            <input
                              type="date"
                              {...register(`passengers.${index}.dateOfBirth`)}
                              className="input-field"
                            />
                            {errors.passengers?.[index]?.dateOfBirth && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.dateOfBirth?.message}</p>
                            )}
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Gender</label>
                            <select
                              {...register(`passengers.${index}.gender`)}
                              className="input-field"
                            >
                              <option value="">Select gender</option>
                              <option value="Male">Male</option>
                              <option value="Female">Female</option>
                            </select>
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Nationality *</label>
                            <input
                              {...register(`passengers.${index}.nationality`)}
                              className="input-field bg-gray-100 dark:bg-gray-700 cursor-not-allowed"
                              readOnly
                              disabled
                            />
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Phone Number</label>
                            <input
                              {...register(`passengers.${index}.phone`)}
                              className="input-field"
                              placeholder="+251911234567"
                            />
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Email</label>
                            <input
                              type="email"
                              {...register(`passengers.${index}.email`)}
                              className="input-field"
                              placeholder="email@example.com"
                            />
                            {errors.passengers?.[index]?.email && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.email?.message}</p>
                            )}
                          </div>
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="grid md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Full Name *</label>
                            <input
                              {...register(`passengers.${index}.name`)}
                              className="input-field"
                              placeholder="Full name as per passport"
                            />
                            {errors.passengers?.[index]?.name && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.name?.message}</p>
                            )}
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Date of Birth *</label>
                            <input
                              type="date"
                              {...register(`passengers.${index}.dateOfBirth`)}
                              className="input-field"
                            />
                            {errors.passengers?.[index]?.dateOfBirth && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.dateOfBirth?.message}</p>
                            )}
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Gender</label>
                            <select
                              {...register(`passengers.${index}.gender`)}
                              className="input-field"
                            >
                              <option value="">Select gender</option>
                              <option value="Male">Male</option>
                              <option value="Female">Female</option>
                            </select>
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Nationality *</label>
                            <input
                              {...register(`passengers.${index}.nationality`)}
                              className="input-field bg-gray-100 dark:bg-gray-700 cursor-not-allowed"
                              readOnly
                              disabled
                            />
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Phone Number</label>
                            <input
                              {...register(`passengers.${index}.phone`)}
                              className="input-field"
                              placeholder="+254712345678"
                            />
                          </div>

                          <div>
                            <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Email</label>
                            <input
                              type="email"
                              {...register(`passengers.${index}.email`)}
                              className="input-field"
                              placeholder="email@example.com"
                            />
                            {errors.passengers?.[index]?.email && (
                              <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.email?.message}</p>
                            )}
                          </div>
                        </div>

                        <div className="border-t dark:border-gray-700 pt-4 mt-4">                          
                          <div className="grid md:grid-cols-2 gap-4">
                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Passport Number *</label>
                              <input
                                {...register(`passengers.${index}.passportNumber`)}
                                className="input-field"
                                placeholder="P1234567"
                              />
                              {errors.passengers?.[index]?.passportNumber && (
                                <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.passportNumber?.message}</p>
                              )}
                            </div>

                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Passport Country *</label>
                              <input
                                {...register(`passengers.${index}.passportCountry`)}
                                className="input-field"
                                placeholder="Djibouti"
                              />
                              {errors.passengers?.[index]?.passportCountry && (
                                <p className="text-red-500 dark:text-red-400 text-sm mt-1">{errors.passengers[index]?.passportCountry?.message}</p>
                              )}
                            </div>

                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Issuing Authority</label>
                              <input
                                {...register(`passengers.${index}.passportIssuingAuthority`)}
                                className="input-field"
                                placeholder="Government of Djibouti"
                              />
                            </div>

                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Issue Date</label>
                              <input
                                type="date"
                                {...register(`passengers.${index}.passportIssueDate`)}
                                className="input-field"
                              />
                            </div>

                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Expiry Date</label>
                              <input
                                type="date"
                                {...register(`passengers.${index}.passportExpiryDate`)}
                                className="input-field"
                              />
                            </div>
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                  )}
                </div>
              );
            })}

            <div className="card">
              <label className="flex items-center gap-2 cursor-pointer">
                <input type="checkbox" {...register('createAccount')} className="w-4 h-4" />
                <span className="text-sm text-gray-700 dark:text-gray-300">Create an account to save my profile for future bookings</span>
              </label>
            </div>

            <div className="flex gap-4">
              <button type="button" onClick={() => router.back()} className="btn-secondary flex-1" disabled={saving}>
                Back
              </button>
              <button type="submit" className="btn-primary flex-1" disabled={saving}>
                {saving ? 'Saving...' : 'Continue to Seat Selection'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
