'use client';

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, useRef } from 'react';
import { CheckCircle, ExternalLink, Loader2, CalendarDays, X, Globe } from 'lucide-react';
import { gregorianToEthiopian, ethiopianToGregorian, ETHIOPIAN_MONTHS, getDaysInEthiopianMonth } from '@/lib/ethiopian-calendar';

const GC_MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];

function daysInGCMonth(y: number, m: number) {
  return new Date(y, m, 0).getDate();
}

function DobPickerModal({
  value,
  onChange,
  error,
}: {
  value: string;
  onChange: (iso: string) => void;
  error?: string;
}) {
  const [open, setOpen] = useState(false);
  const [manualMode, setManualMode] = useState(false);
  const [calType, setCalType] = useState<'gregorian' | 'ethiopian'>('gregorian');
  const currentYear = new Date().getFullYear();
  const currentEthYear = gregorianToEthiopian(new Date()).year;

  // Parse stored ISO value (always Gregorian)
  const parsed = value ? value.split('-') : [];
  const initGCYear  = parsed[0] ? parseInt(parsed[0]) : currentYear - 25;
  const initGCMonth = parsed[1] ? parseInt(parsed[1]) : 1;
  const initGCDay   = parsed[2] ? parseInt(parsed[2]) : 1;

  // Gregorian drum state
  const [selGCYear,  setSelGCYear]  = useState(initGCYear);
  const [selGCMonth, setSelGCMonth] = useState(initGCMonth);
  const [selGCDay,   setSelGCDay]   = useState(initGCDay);

  // Ethiopian drum state — initialise from parsed value if present
  const initEth = value ? gregorianToEthiopian(new Date(initGCYear, initGCMonth - 1, initGCDay)) : { year: currentEthYear - 25, month: 1, day: 1 };
  const [selEthYear,  setSelEthYear]  = useState(initEth.year);
  const [selEthMonth, setSelEthMonth] = useState(initEth.month);
  const [selEthDay,   setSelEthDay]   = useState(initEth.day);

  // Manual inputs
  const [manDay,   setManDay]   = useState(parsed[2] ? String(parseInt(parsed[2])) : '');
  const [manMonth, setManMonth] = useState(parsed[1] ? String(parseInt(parsed[1])) : '');
  const [manYear,  setManYear]  = useState(parsed[0] || '');

  // Computed
  const gcMaxDay  = daysInGCMonth(selGCYear, selGCMonth);
  const ethMaxDay = getDaysInEthiopianMonth(selEthYear, selEthMonth);
  const gcSafeDay  = Math.min(selGCDay,  gcMaxDay);
  const ethSafeDay = Math.min(selEthDay, ethMaxDay);

  const gcYears   = Array.from({ length: 100 }, (_, i) => currentYear - i);
  const ethYears  = Array.from({ length: 100 }, (_, i) => currentEthYear - i);
  const gcMonths  = GC_MONTHS.map((m, i) => ({ label: m, value: i + 1 }));
  const ethMonths = ETHIOPIAN_MONTHS.map((m, i) => ({ label: m, value: i + 1 }));
  const gcDays    = Array.from({ length: gcMaxDay  }, (_, i) => i + 1);
  const ethDays   = Array.from({ length: ethMaxDay }, (_, i) => i + 1);

  const dayRef   = useRef<HTMLDivElement>(null);
  const monthRef = useRef<HTMLDivElement>(null);
  const yearRef  = useRef<HTMLDivElement>(null);
  const ITEM_H   = 48;

  const scrollTo = (ref: React.RefObject<HTMLDivElement>, idx: number) => {
    ref.current?.scrollTo({ top: Math.max(0, idx) * ITEM_H, behavior: 'smooth' });
  };

  // Scroll drums to current selection when opened or calType changed
  useEffect(() => {
    if (!open || manualMode) return;
    setTimeout(() => {
      if (calType === 'gregorian') {
        scrollTo(dayRef,   gcSafeDay - 1);
        scrollTo(monthRef, selGCMonth - 1);
        scrollTo(yearRef,  gcYears.indexOf(selGCYear));
      } else {
        scrollTo(dayRef,   ethSafeDay - 1);
        scrollTo(monthRef, selEthMonth - 1);
        scrollTo(yearRef,  ethYears.indexOf(selEthYear));
      }
    }, 60);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, manualMode, calType]);

  const makeScrollHandler = (
    ref: React.RefObject<HTMLDivElement>,
    setter: (v: number) => void,
    getList: () => number[],
  ) => {
    let timer: ReturnType<typeof setTimeout>;
    return () => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        const el = ref.current;
        if (!el) return;
        const list = getList();
        const idx = Math.round(el.scrollTop / ITEM_H);
        const clamped = Math.max(0, Math.min(idx, list.length - 1));
        setter(list[clamped]);
        el.scrollTo({ top: clamped * ITEM_H, behavior: 'smooth' });
      }, 150);
    };
  };

  const gcDayHandler   = useRef(makeScrollHandler(dayRef,   setSelGCDay,   () => Array.from({ length: daysInGCMonth(selGCYear, selGCMonth) }, (_, i) => i + 1))).current;
  const gcMonthHandler = useRef(makeScrollHandler(monthRef, setSelGCMonth, () => GC_MONTHS.map((_, i) => i + 1))).current;
  const gcYearHandler  = useRef(makeScrollHandler(yearRef,  setSelGCYear,  () => Array.from({ length: 100 }, (_, i) => new Date().getFullYear() - i))).current;

  const ethDayHandler   = useRef(makeScrollHandler(dayRef,   setSelEthDay,   () => Array.from({ length: getDaysInEthiopianMonth(selEthYear, selEthMonth) }, (_, i) => i + 1))).current;
  const ethMonthHandler = useRef(makeScrollHandler(monthRef, setSelEthMonth, () => ETHIOPIAN_MONTHS.map((_, i) => i + 1))).current;
  const ethYearHandler  = useRef(makeScrollHandler(yearRef,  setSelEthYear,  () => Array.from({ length: 100 }, (_, i) => gregorianToEthiopian(new Date()).year - i))).current;

  const confirm = () => {
    let gregDate: Date;
    if (calType === 'gregorian') {
      const d = Math.min(selGCDay, daysInGCMonth(selGCYear, selGCMonth));
      gregDate = new Date(selGCYear, selGCMonth - 1, d);
    } else {
      const d = Math.min(selEthDay, getDaysInEthiopianMonth(selEthYear, selEthMonth));
      gregDate = ethiopianToGregorian({ year: selEthYear, month: selEthMonth, day: d });
    }
    const iso = `${gregDate.getFullYear()}-${String(gregDate.getMonth() + 1).padStart(2,'0')}-${String(gregDate.getDate()).padStart(2,'0')}`;
    onChange(iso);
    setOpen(false);
  };

  const confirmManual = () => {
    const d = parseInt(manDay), m = parseInt(manMonth), y = parseInt(manYear);
    if (!d || !m || !y || m < 1 || m > 12 || d < 1 || d > daysInGCMonth(y, m) || y < currentYear - 110 || y > currentYear) return;
    onChange(`${y}-${String(m).padStart(2,'0')}-${String(d).padStart(2,'0')}`);
    setOpen(false);
  };

  const manualValid = (() => {
    const d = parseInt(manDay), m = parseInt(manMonth), y = parseInt(manYear);
    return d >= 1 && m >= 1 && m <= 12 && y >= currentYear - 110 && y <= currentYear && d <= daysInGCMonth(y, m);
  })();

  // Display: always show Gregorian ISO as human-readable, with calendar label
  const displayValue = (() => {
    if (!value) return '';
    const [y, mo, d] = value.split('-').map(Number);
    const gcStr = `${GC_MONTHS[mo - 1]} ${d}, ${y}`;
    if (calType === 'ethiopian') {
      const eth = gregorianToEthiopian(new Date(y, mo - 1, d));
      return `${ETHIOPIAN_MONTHS[eth.month - 1]} ${eth.day}, ${eth.year} (${gcStr})`;
    }
    return gcStr;
  })();

  // Confirm button label
  const confirmLabel = (() => {
    if (manualMode) return manualValid ? `Confirm — ${manDay}/${manMonth}/${manYear}` : 'Confirm';
    if (calType === 'gregorian') {
      const d = Math.min(selGCDay, gcMaxDay);
      return `Confirm — ${GC_MONTHS[selGCMonth - 1]} ${d}, ${selGCYear}`;
    } else {
      const d = Math.min(selEthDay, ethMaxDay);
      const gcDate = ethiopianToGregorian({ year: selEthYear, month: selEthMonth, day: d });
      return `Confirm — ${ETHIOPIAN_MONTHS[selEthMonth - 1]} ${d}, ${selEthYear} (GC: ${GC_MONTHS[gcDate.getMonth()]} ${gcDate.getDate()}, ${gcDate.getFullYear()})`;
    }
  })();

  const col = (
    ref: React.RefObject<HTMLDivElement>,
    list: Array<{ label: string; value: number }>,
    selected: number,
    setter: (v: number) => void,
    scrollHandler: () => void,
  ) => (
    <div className="flex-1 flex flex-col items-center">
      <div
        ref={ref}
        onScroll={scrollHandler}
        className="h-full overflow-y-auto scrollbar-hide"
        style={{ scrollSnapType: 'y mandatory' }}
      >
        <div style={{ height: ITEM_H * 2 }} />
        {list.map((item, idx) => (
          <div
            key={item.value}
            style={{ height: ITEM_H, scrollSnapAlign: 'center', cursor: 'pointer' }}
            onClick={() => { setter(item.value); ref.current?.scrollTo({ top: idx * ITEM_H, behavior: 'smooth' }); }}
            className={`flex items-center justify-center text-sm font-medium transition-all select-none ${
              item.value === selected ? 'text-primary font-bold text-base' : 'text-gray-400 dark:text-gray-500'
            }`}
          >
            {item.label}
          </div>
        ))}
        <div style={{ height: ITEM_H * 2 }} />
      </div>
    </div>
  );

  return (
    <div>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={`input-field w-full text-left flex items-center justify-between ${
          error ? 'border-red-500' : ''
        }`}
      >
        <span className={displayValue ? 'text-gray-900 dark:text-white text-sm' : 'text-gray-400 text-sm'}>
          {displayValue || 'Select date of birth'}
        </span>
        <CalendarDays className="w-4 h-4 text-gray-400 flex-shrink-0" />
      </button>
      {error && <p className="text-red-500 text-xs mt-1">{error}</p>}

      {open && (
        <>
          <div className="fixed inset-0 z-[99] bg-black/50" onClick={() => setOpen(false)} />
          <div
            className="fixed inset-x-0 bottom-0 z-[100] bg-white dark:bg-gray-900 rounded-t-2xl shadow-2xl"
            style={{ animation: 'dob-slide-up 0.25s cubic-bezier(0.32,0.72,0,1)' }}
          >
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100 dark:border-gray-800">
              <div className="flex items-center gap-3">
                <h2 className="text-base font-bold text-gray-900 dark:text-white">Date of Birth</h2>
                {!manualMode && (
                  <button
                    type="button"
                    onClick={() => setCalType(c => c === 'gregorian' ? 'ethiopian' : 'gregorian')}
                    className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
                  >
                    <Globe className="w-3 h-3" />
                    {calType === 'gregorian' ? 'ET' : 'GC'}
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => setManualMode(!manualMode)}
                  className="text-xs text-gray-500 font-medium hover:underline"
                >
                  {manualMode ? 'Use scroll' : 'Enter manually'}
                </button>
              </div>
              <button type="button" onClick={() => setOpen(false)} className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* Calendar type label */}
            {!manualMode && (
              <div className="px-5 pt-2 pb-0">
                <p className="text-xs text-gray-400">
                  {calType === 'gregorian' ? 'Gregorian Calendar' : 'Ethiopian Calendar (ኢትዮጵያ)'}
                </p>
              </div>
            )}

            {manualMode ? (
              <div className="px-5 py-5 space-y-4">
                <div className="grid grid-cols-3 gap-3">
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Day</label>
                    <input type="number" min={1} max={31} value={manDay} onChange={(e) => setManDay(e.target.value)} placeholder="DD" className="input-field text-center text-lg font-semibold" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Month</label>
                    <input type="number" min={1} max={12} value={manMonth} onChange={(e) => setManMonth(e.target.value)} placeholder="MM" className="input-field text-center text-lg font-semibold" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">Year</label>
                    <input type="number" min={currentYear - 110} max={currentYear} value={manYear} onChange={(e) => setManYear(e.target.value)} placeholder="YYYY" className="input-field text-center text-lg font-semibold" />
                  </div>
                </div>
                {manDay && manMonth && manYear && !manualValid && (
                  <p className="text-red-500 text-xs">Please enter a valid Gregorian date</p>
                )}
              </div>
            ) : (
              <>
                <div className="flex px-5 pt-2 pb-1">
                  {['Day', 'Month', 'Year'].map(l => (
                    <div key={l} className="flex-1 text-center text-xs font-semibold text-gray-400 uppercase tracking-wide">{l}</div>
                  ))}
                </div>
                <div className="relative px-5 pb-2" style={{ height: ITEM_H * 5 }}>
                  <div
                    className="absolute left-5 right-5 pointer-events-none rounded-xl border border-primary/30 bg-primary/5 dark:bg-primary/10"
                    style={{ top: ITEM_H * 2, height: ITEM_H }}
                  />
                  <div className="flex gap-2 h-full">
                    {calType === 'gregorian' ? (
                      <>
                        {col(dayRef,   gcDays.map(d => ({ label: String(d), value: d })), gcSafeDay,   setSelGCDay,   gcDayHandler)}
                        {col(monthRef, gcMonths,                                           selGCMonth,  setSelGCMonth, gcMonthHandler)}
                        {col(yearRef,  gcYears.map(y => ({ label: String(y), value: y })), selGCYear,   setSelGCYear,  gcYearHandler)}
                      </>
                    ) : (
                      <>
                        {col(dayRef,   ethDays.map(d => ({ label: String(d), value: d })), ethSafeDay,  setSelEthDay,   ethDayHandler)}
                        {col(monthRef, ethMonths,                                            selEthMonth, setSelEthMonth, ethMonthHandler)}
                        {col(yearRef,  ethYears.map(y => ({ label: String(y), value: y })), selEthYear,  setSelEthYear,  ethYearHandler)}
                      </>
                    )}
                  </div>
                </div>
              </>
            )}

            <div className="px-5 pb-8 pt-3 flex justify-end">
              <button
                type="button"
                onClick={manualMode ? confirmManual : confirm}
                disabled={manualMode && !manualValid}
                className="px-6 py-2.5 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-bold text-sm rounded-xl transition-all shadow disabled:opacity-40 disabled:cursor-not-allowed"
              >
                {confirmLabel}
              </button>
            </div>
          </div>
          <style>{`@keyframes dob-slide-up{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}`}</style>
        </>
      )}
    </div>
  );
}

const passengerSchema = z.object({
  name: z.string().min(2, 'Full name is required (min 2 characters)'),
  dateOfBirth: z.string().min(1, 'Date of birth is required'),
  gender: z.string().min(1, 'Gender is required'),
  nationality: z.string().min(1, 'Nationality is required'),
  phone: z.string().min(1, 'Phone number is required'),
  email: z.string().optional(),
  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(),
}).superRefine((data, ctx) => {
  if (data.gender !== 'Male' && data.gender !== 'Female') {
    ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Gender is required', path: ['gender'] });
  }
  if (data.email && data.email.trim().length > 0) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(data.email)) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid email format', path: ['email'] });
    }
  }
  const isNonEthiopian = data.nationality !== 'ETHIOPIAN' && data.nationality !== 'Ethiopian';
  if (isNonEthiopian) {
    if (!data.passportNumber || data.passportNumber.trim().length === 0) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Passport number is required', path: ['passportNumber'] });
    }
    if (!data.passportCountry || data.passportCountry.trim().length === 0) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Issuing country is required', path: ['passportCountry'] });
    }
  }
});

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 [saving, setSaving] = useState(false);
  const [formInitialized, setFormInitialized] = useState(false);


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

  const { register, control, handleSubmit, setValue, watch, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(formSchema as any),
    mode: 'onChange',
    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();
  }, []);

  useEffect(() => {
    if (isAuthenticated && user?.faydaVerified) {
      setVerificationStatus({ 0: 'success' });
    }
  }, [isAuthenticated, user?.faydaVerified]);

  useEffect(() => {
    const populateForm = async () => {
      if (!isAuthenticated || !user?.id || !searchCriteria) {
        console.log('Missing required data for population');
        setFormInitialized(true);
        return;
      }

      try {
        // Fetch passenger profile from backend
        const passengerData: any = await apiClient.get(`/passengers/me`);
        console.log('Fetched passenger data:', passengerData);

        if (!passengerData) {
          setFormInitialized(true);
          return;
        }

        // Only populate first passenger
        console.log('Setting passenger 0 values');
        setValue('passengers.0.name', passengerData?.fullName || user.fullName || '');
        setValue('passengers.0.dateOfBirth', passengerData?.dateOfBirth || user.dateOfBirth || '');
        if (passengerData?.gender || user.gender) setValue('passengers.0.gender', (passengerData?.gender || user.gender) as any);
        setValue('passengers.0.nationality', passengerData?.nationality || user.nationality || 'ETHIOPIAN');
        if (passengerData?.phone || user.phone) setValue('passengers.0.phone', passengerData?.phone || user.phone || '');
        if (passengerData?.email || user.email) setValue('passengers.0.email', passengerData?.email || user.email || '');
        if (passengerData?.passportNumber) setValue('passengers.0.passportNumber', passengerData.passportNumber);
        if (passengerData?.passportCountry) setValue('passengers.0.passportCountry', passengerData.passportCountry);
        if (passengerData?.passportIssueDate) setValue('passengers.0.passportIssueDate', passengerData.passportIssueDate);
        if (passengerData?.passportExpiryDate) setValue('passengers.0.passportExpiryDate', passengerData.passportExpiryDate);
        if (passengerData?.passportIssuingAuthority) setValue('passengers.0.passportIssuingAuthority', passengerData.passportIssuingAuthority);
        setValue('passengers.0.faydaVerified', passengerData?.faydaVerified || user.faydaVerified || false);
        setValue('passengers.0.formExpanded', true);

        setFormInitialized(true);
      } catch (error) {
        console.error('Failed to fetch passenger data:', error);
        setFormInitialized(true);
      }
    };

    populateForm();
  }, [isAuthenticated, user, searchCriteria, setValue]);

  const openFaydaVerification = async (index: number) => {
    if (typeof window === 'undefined') return;

    try {
      const response: any = await apiClient.post('/fayda/verification/start', {
        purpose: 'PURCHASE',
        platform: 'WEB',
        saveToAccount: index === 0 && isAuthenticated,
      });

      const authorizationUrl = response.authorizationUrl;
      const width = 600;
      const height = 700;
      const left = (window.screen.width - width) / 2;
      const top = (window.screen.height - height) / 2;

      const popup = window.open(
        authorizationUrl,
        'FaydaVerification',
        `width=${width},height=${height},left=${left},top=${top},scrollbars=yes,resizable=yes`
      );

      const checkPopup = setInterval(async () => {
        if (popup?.closed) {
          clearInterval(checkPopup);
          try {
            const statusResponse: any = await apiClient.get('/fayda/verification/status');
            if (statusResponse.verified) {
              setValue(`passengers.${index}.name`, statusResponse.fullName || '');
              setValue(`passengers.${index}.faydaVerified`, true);
              setValue(`passengers.${index}.formExpanded`, true);
              setVerificationStatus({ ...verificationStatus, [index]: 'success' });

              if (index === 0 && isAuthenticated) {
                updateUser({
                  fullName: statusResponse.fullName,
                  faydaVerified: true,
                  faydaVerifiedAt: statusResponse.verifiedAt,
                });
              }
            }
          } catch (error) {
            console.error('Failed to get verification status:', error);
          }
        }
      }, 1000);
    } catch (error) {
      console.error('Failed to start Fayda verification:', error);
      alert('Failed to start verification. Please try again.');
    }
  };

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

  const onSubmit = async (data: FormData) => {
    setSaving(true);
    try {
      let passengerId = '';
      
      // For authenticated users, fetch the passenger profile to get the passengerId
      if (isAuthenticated && user?.id) {
        try {
          const passengerProfile: any = await apiClient.get('/passengers/me');
          passengerId = passengerProfile?.id || '';
          console.log('Fetched passengerId:', passengerId);
        } catch (error) {
          console.error('Failed to fetch passenger profile:', error);
        }
      }

      const passengerDetails = data.passengers.map((p, i) => ({
        name: p.name,
        dateOfBirth: p.dateOfBirth,
        gender: p.gender,
        nationality: p.nationality,
        nationalId: p.nationalId,
        passportNumber: p.passportNumber,
        passportCountry: p.passportCountry,
        passportIssueDate: p.passportIssueDate,
        passportExpiryDate: p.passportExpiryDate,
        passportIssuingAuthority: p.passportIssuingAuthority,
        phone: p.phone || '',
        email: p.email || '',
        isPrimaryPassenger: i === 0,
        passengerId: i === 0 && passengerId ? passengerId : undefined,
      }))

      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);
      
      // Save passengerId to booking store for later use
      if (isAuthenticated && passengerId) {
        const { setPassengerId } = useBookingStore.getState();
        setPassengerId(passengerId);
        console.log('Saved passengerId to booking store:', passengerId);
      }
      
      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);
    }
  };

  useEffect(() => {
    if (!searchCriteria) {
      router.push('/booking/search');
    }
  }, [searchCriteria, router]);

  if (!searchCriteria) return null;

  if (!formInitialized) {
    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-lg mx-auto text-center">
            <Loader2 className="w-8 h-8 animate-spin mx-auto text-blue-600" />
            <p className="text-gray-600 dark:text-gray-400 mt-4">Loading passenger details...</p>
          </div>
        </div>
      </div>
    );
  }

  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-6xl 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' : 'Other'})
                    </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"
                      >
                        <ExternalLink className="w-5 h-5" />
                        {isLoggedInNotVerified ? 'Verify with Fayda' : 'Verify with Fayda'}
                      </button>
                      <button
                        type="button"
                        onClick={() => toggleForm(index)}
                        className="text-sm text-gray-500 dark:text-gray-400 hover:underline mt-3 block mx-auto"
                      >
                        Skip for now
                      </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">
                            {/* Full Name */}
                            <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 ${errors.passengers?.[index]?.name ? 'border-red-500' : ''}`}
                                placeholder="Full name as per ID"
                              />
                              {errors.passengers?.[index]?.name && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.name?.message}</p>
                              )}
                            </div>

                            {/* Date of Birth */}
                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Date of Birth *</label>
                              <DobPickerModal
                                value={passengers[index]?.dateOfBirth || ''}
                                onChange={(iso) => setValue(`passengers.${index}.dateOfBirth`, iso, { shouldValidate: true })}
                                error={errors.passengers?.[index]?.dateOfBirth?.message}
                              />
                            </div>

                            {/* Gender */}
                            <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 ${errors.passengers?.[index]?.gender ? 'border-red-500' : ''}`}
                              >
                                <option value="">Select gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                              </select>
                              {errors.passengers?.[index]?.gender && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.gender?.message}</p>
                              )}
                            </div>

                            {/* Nationality (read-only) */}
                            <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>

                            {/* Phone */}
                            <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 ${errors.passengers?.[index]?.phone ? 'border-red-500' : ''}`}
                                placeholder="+251911234567"
                              />
                              {errors.passengers?.[index]?.phone && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.phone?.message}</p>
                              )}
                            </div>

                            {/* Email */}
                            <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 ${errors.passengers?.[index]?.email ? 'border-red-500' : ''}`}
                                placeholder="email@example.com"
                              />
                              {errors.passengers?.[index]?.email && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.email?.message}</p>
                              )}
                            </div>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="grid md:grid-cols-2 gap-4">
                            {/* Full Name */}
                            <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 ${errors.passengers?.[index]?.name ? 'border-red-500' : ''}`}
                                placeholder="Full name as per passport"
                              />
                              {errors.passengers?.[index]?.name && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.name?.message}</p>
                              )}
                            </div>

                            {/* Date of Birth */}
                            <div>
                              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Date of Birth *</label>
                              <DobPickerModal
                                value={passengers[index]?.dateOfBirth || ''}
                                onChange={(iso) => setValue(`passengers.${index}.dateOfBirth`, iso, { shouldValidate: true })}
                                error={errors.passengers?.[index]?.dateOfBirth?.message}
                              />
                            </div>

                            {/* Gender */}
                            <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 ${errors.passengers?.[index]?.gender ? 'border-red-500' : ''}`}
                              >
                                <option value="">Select gender</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                              </select>
                              {errors.passengers?.[index]?.gender && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.gender?.message}</p>
                              )}
                            </div>

                            {/* Nationality (read-only) */}
                            <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>

                            {/* Phone */}
                            <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 ${errors.passengers?.[index]?.phone ? 'border-red-500' : ''}`}
                                placeholder="+254712345678"
                              />
                              {errors.passengers?.[index]?.phone && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.phone?.message}</p>
                              )}
                            </div>

                            {/* Email */}
                            <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 ${errors.passengers?.[index]?.email ? 'border-red-500' : ''}`}
                                placeholder="email@example.com"
                              />
                              {errors.passengers?.[index]?.email && (
                                <p className="text-red-500 text-xs mt-1">{errors.passengers[index]?.email?.message}</p>
                              )}
                            </div>
                          </div>

                          {/* Passport fields */}
                          <div className="border-t dark:border-gray-700 pt-4 mt-4">
                            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">Passport Details</h4>
                            <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 ${errors.passengers?.[index]?.passportNumber ? 'border-red-500' : ''}`}
                                  placeholder="P1234567"
                                />
                                {errors.passengers?.[index]?.passportNumber && (
                                  <p className="text-red-500 text-xs 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">Issuing Country *</label>
                                <input
                                  {...register(`passengers.${index}.passportCountry`)}
                                  className={`input-field ${errors.passengers?.[index]?.passportCountry ? 'border-red-500' : ''}`}
                                  placeholder="e.g., Djibouti"
                                />
                                {errors.passengers?.[index]?.passportCountry && (
                                  <p className="text-red-500 text-xs 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">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>
              );
            })}
            
            {!isAuthenticated && (
              <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={() => {
                const params = new URLSearchParams({
                  origin: searchCriteria.originStationId,
                  destination: searchCriteria.destinationStationId,
                  date: searchCriteria.departureDate,
                  adults: String(searchCriteria.adultCount),
                  children: String(searchCriteria.childCount),
                  nationality: searchCriteria.nationality,
                  ...(searchCriteria.promoCode && { promoCode: searchCriteria.promoCode }),
                });
                router.push(`/booking/results?${params}`);
              }} 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>
  );
}
