'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import React, { useEffect, useState } from 'react';
import { toast } from 'sonner';

interface PatientFormProps {
  initialData?: {
    _id?: string;
    userId?: {
      firstName?: string;
      lastName?: string;
      email?: string;
      phone?: string;
    };
    phone?: string;
    gender?: string;
    dateOfBirth?: string;
    address?: string;
    medicalHistory?: string;
    nationalId?: string;
    insurance?: {
      provider?: string;
      policyNumber?: string;
    };
  } | null;
  onSuccess?: () => void;
  onCancel?: () => void;
}

interface PatientFormData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  gender: string;
  dateOfBirth: string;
  address: string;
  medicalHistory: string;
  nationalId: string;
  insuranceProvider: string;
  insurancePolicyNumber: string;
}

export default function PatientForm({ initialData, onSuccess, onCancel }: PatientFormProps) {
  const { t } = useLanguage();
  const { token } = useAuthStore();
  const [loading, setLoading] = useState(false);

  // Extract YYYY-MM-DD from a date string safely in UTC (avoids timezone shift)
  const toDateInputValue = (d?: string) => {
    if (!d) return '';
    const date = new Date(d);
    const y = date.getUTCFullYear();
    const m = String(date.getUTCMonth() + 1).padStart(2, '0');
    const day = String(date.getUTCDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  };

  const [formData, setFormData] = useState<PatientFormData>(() => {
    if (initialData) {
      return {
        firstName: initialData.userId?.firstName || '',
        lastName: initialData.userId?.lastName || '',
        email: initialData.userId?.email || '',
        phone: initialData.userId?.phone || initialData.phone || '',
        gender: initialData.gender ? initialData.gender.trim().charAt(0).toUpperCase() + initialData.gender.trim().slice(1).toLowerCase() : '',
        dateOfBirth: toDateInputValue(initialData.dateOfBirth),
        address: initialData.address || '',
        medicalHistory: initialData.medicalHistory || '',
        nationalId: initialData.nationalId || '',
        insuranceProvider: initialData.insurance?.provider || '',
        insurancePolicyNumber: initialData.insurance?.policyNumber || '',
      };
    }
    return {
      firstName: '',
      lastName: '',
      email: '',
      phone: '',
      gender: '',
      dateOfBirth: '',
      address: '',
      medicalHistory: '',
      nationalId: '',
      insuranceProvider: '',
      insurancePolicyNumber: '',
    };
  });

  useEffect(() => {
    if (initialData) {
      setFormData({
        firstName: initialData.userId?.firstName || '',
        lastName: initialData.userId?.lastName || '',
        email: initialData.userId?.email || '',
        phone: initialData.userId?.phone || initialData.phone || '',
        gender: initialData.gender ? initialData.gender.trim().charAt(0).toUpperCase() + initialData.gender.trim().slice(1).toLowerCase() : '',
        dateOfBirth: toDateInputValue(initialData.dateOfBirth),
        address: initialData.address || '',
        medicalHistory: initialData.medicalHistory || '',
        nationalId: initialData.nationalId || '',
        insuranceProvider: initialData.insurance?.provider || '',
        insurancePolicyNumber: initialData.insurance?.policyNumber || '',
      });
    } else {
      setFormData({
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        gender: '',
        dateOfBirth: '',
        address: '',
        medicalHistory: '',
        nationalId: '',
        insuranceProvider: '',
        insurancePolicyNumber: '',
      });
    }
  }, [initialData]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSelectChange = (name: string, value: string) => {
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!formData.firstName.trim() || !formData.lastName.trim()) {
      toast.error(t('patients.nameRequired'));
      return;
    }

    const normalizedEmail = formData.email.trim().toLowerCase();

    if (!normalizedEmail) {
      toast.error(t('patients.emailRequired'));
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) {
      toast.error(t('errors.invalidEmail'));
      return;
    }

    if (formData.dateOfBirth) {
      const dob = new Date(formData.dateOfBirth + 'T00:00:00Z');
      if (isNaN(dob.getTime()) || dob > new Date()) {
        toast.error(t('patients.invalidDateOfBirth'));
        return;
      }
    }

    setLoading(true);

    try {
      const url = initialData?._id
        ? `${API_BASE_URL}/api/patients/${initialData._id}`
        : `${API_BASE_URL}/api/patients`;

      const method = initialData?._id ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token || '',
        },
        body: JSON.stringify({
          firstName: formData.firstName,
          lastName: formData.lastName,
          email: normalizedEmail,
          phone: formData.phone,
          gender: formData.gender,
          dateOfBirth: formData.dateOfBirth ? formData.dateOfBirth + 'T00:00:00Z' : undefined,
          address: formData.address,
          medicalHistory: formData.medicalHistory,
          nationalId: formData.nationalId,
          insurance: formData.insuranceProvider || formData.insurancePolicyNumber
            ? {
              provider: formData.insuranceProvider,
              policyNumber: formData.insurancePolicyNumber,
            }
            : undefined,
        }),
      });

      const result = await response.json();

      if (response.ok) {
        toast.success(initialData ? t('patients.patientUpdated') : t('patients.patientCreated'));
        onSuccess?.();
      } else {
        toast.error(result.error || t('patients.saveFailed'));
      }
    } catch (error) {
      console.error('Error creating patient:', error);
      toast.error(t('common.unexpectedError'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="py-4">
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <Label htmlFor="firstName" className="font-semibold text-foreground/80">{t('auth.firstName')}</Label>
            <Input
              id="firstName"
              name="firstName"
              value={formData.firstName}
              onChange={handleChange}
              required
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="lastName" className="font-semibold text-foreground/80">{t('auth.lastName')}</Label>
            <Input
              id="lastName"
              name="lastName"
              value={formData.lastName}
              onChange={handleChange}
              required
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <Label htmlFor="email" className="font-semibold text-foreground/80">{t('common.email')}</Label>
            <Input
              id="email"
              name="email"
              type="email"
              value={formData.email}
              onChange={handleChange}
              required
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone" className="font-semibold text-foreground/80">{t('common.phone')}</Label>
            <Input
              id="phone"
              name="phone"
              value={formData.phone}
              onChange={handleChange}
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <Label htmlFor="gender" className="font-semibold text-foreground/80">{t('common.gender')}</Label>
            <Select value={formData.gender} onValueChange={(value) => handleSelectChange('gender', value)}>
              <SelectTrigger className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white">
                <SelectValue placeholder={t('auth.selectUserType')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="Male">{t('common.male')}</SelectItem>
                <SelectItem value="Female">{t('common.female')}</SelectItem>
                <SelectItem value="Other">{t('common.other')}</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="dateOfBirth" className="font-semibold text-foreground/80">{t('common.dateOfBirth')}</Label>
            <Input
              id="dateOfBirth"
              name="dateOfBirth"
              type="date"
              value={formData.dateOfBirth}
              onChange={handleChange}
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="address" className="font-semibold text-foreground/80">{t('common.address')}</Label>
          <Input
            id="address"
            name="address"
            value={formData.address}
            onChange={handleChange}
            className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="space-y-2">
            <Label htmlFor="nationalId" className="font-semibold text-foreground/80">{t('patients.nationalId')}</Label>
            <Input
              id="nationalId"
              name="nationalId"
              value={formData.nationalId}
              onChange={handleChange}
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="insuranceProvider" className="font-semibold text-foreground/80">{t('patients.insurance')}</Label>
            <Input
              id="insuranceProvider"
              name="insuranceProvider"
              value={formData.insuranceProvider}
              onChange={handleChange}
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="insurancePolicyNumber" className="font-semibold text-foreground/80">{t('patients.policyNumber')}</Label>
            <Input
              id="insurancePolicyNumber"
              name="insurancePolicyNumber"
              value={formData.insurancePolicyNumber}
              onChange={handleChange}
              className="h-11 rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all"
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="medicalHistory" className="font-semibold text-foreground/80">{t('patients.medicalHistory')}</Label>
          <Textarea
            id="medicalHistory"
            name="medicalHistory"
            value={formData.medicalHistory}
            onChange={handleChange}
            placeholder={t('patients.patientHistory')}
            className="min-h-[100px] rounded-lg bg-gray-50/50 border-gray-200 focus:bg-white transition-all resize-y"
          />
        </div>

        <div className="flex justify-end gap-3 pt-4 border-t">
          {onCancel && (
            <Button type="button" variant="outline" onClick={onCancel} className="h-11 px-6 rounded-lg hover:bg-gray-100">
              {t('common.cancel')}
            </Button>
          )}
          <Button type="submit" disabled={loading} className="h-11 px-6 rounded-lg font-semibold shadow-md active:scale-95 transition-all">
            {loading ? t('common.loading') : (initialData ? t('common.save') : t('patients.addPatient'))}
          </Button>
        </div>
      </form>
    </div>
  );
}
