import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useUpdateBasicDetails } from "@/hooks/useProfile";
import { api } from "@/services/api";
import { toast } from "sonner";

interface EditBasicDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
}

export function EditBasicDetailsModal({ isOpen, onClose, user }: EditBasicDetailsModalProps) {
  const profile = user?.seekerProfile || {};
  const address = user?.address || {};
  
  const updateMutation = useUpdateBasicDetails();

  // Local state for the form
  const [formData, setFormData] = useState({
    fullName: user?.full_name || user?.fullName || "",
    jobTitle: profile.profession_id?.toString() || profile.current_job_title || profile.headline || profile.professional_title || "",
    phone: user?.phone || "",
    email: user?.email || "",
    dob: profile.date_of_birth ? new Date(profile.date_of_birth).toISOString().split('T')[0] : "",
    gender: profile.gender || "",
    qualification: profile.qualification || "", 
    experience: profile.experience || "", 
    
    // Address Details
    currentAddress: address.permanent_address || address.street_address || "",
    pincode: address.permanent_pincode || address.postal_code || "",
    area: address.city || "", // Or local area
    state: address.state || "",
    city: address.city || "",
    country: address.country || ""
  });

  const [roles, setRoles] = useState<{ id: number; name: string }[]>([]);
  const [pincodeAreas, setPincodeAreas] = useState<any[]>([]);
  const [educationLevels, setEducationLevels] = useState<{ id: number; name: string }[]>([]);
  const [experiences, setExperiences] = useState<{ id: number; level: string; duration: string | null }[]>([]);

  useEffect(() => {
    if (isOpen) {
      api.get('/roles').then(res => {
        if (res.data) setRoles(res.data);
      }).catch(console.error);
      
      api.get('/education_levels').then(res => {
        if (res.data) setEducationLevels(res.data);
      }).catch(console.error);

      api.get('/experiences').then(res => {
        if (res.data) setExperiences(res.data);
      }).catch(console.error);
    }
  }, [isOpen]);

  // Auto-fetch city, state, country when pincode is 6 digits
  useEffect(() => {
    if (formData.pincode && formData.pincode.length === 6) {
      api.get(`/area/by_pincode?pincode=${formData.pincode}`)
        .then(res => {
          if (res.data && res.data.length > 0) {
            setPincodeAreas(res.data);
            const firstArea = res.data[0];
            setFormData(prev => ({
              ...prev,
              city: firstArea.city_name || prev.city,
              state: firstArea.state_name || prev.state,
              country: firstArea.country_name || prev.country,
              area: firstArea.area || prev.area
            }));
          } else {
            setPincodeAreas([]);
          }
        })
        .catch(console.error);
    } else {
      setPincodeAreas([]);
    }
  }, [formData.pincode]);

  useEffect(() => {
    if (isOpen) {
      setFormData({
        fullName: user?.full_name || user?.fullName || "",
        jobTitle: profile.profession_id?.toString() || profile.current_job_title || profile.headline || profile.professional_title || "",
        phone: user?.phone || "",
        email: user?.email || "",
        dob: profile.date_of_birth ? new Date(profile.date_of_birth).toISOString().split('T')[0] : "",
        gender: profile.gender || "",
        qualification: profile.qualification || "",
        experience: profile.experience || "",
        currentAddress: address.permanent_address || address.street_address || "",
        pincode: address.permanent_pincode || address.postal_code || "",
        area: address.city || "",
        state: address.state || "",
        city: address.city || "",
        country: address.country || ""
      });
    }
  }, [isOpen, user]);

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

  const setGender = (val: string) => setFormData(prev => ({ ...prev, gender: val }));

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (formData.dob) {
      const dob = new Date(formData.dob);
      const today = new Date();
      let age = today.getFullYear() - dob.getFullYear();
      const m = today.getMonth() - dob.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < dob.getDate())) {
        age--;
      }
      if (age < 16) {
        toast.error("You must be at least 16 years old.");
        return;
      }
    }
    
    // Find the role name to store as professional_title
    const selectedRole = roles.find(r => r.id.toString() === formData.jobTitle.toString());

    updateMutation.mutate({
      fullName: formData.fullName,
      phone: formData.phone,
      email: formData.email,
      profession_id: selectedRole ? selectedRole.id : undefined,
      professional_title: selectedRole ? selectedRole.name : formData.jobTitle,
      date_of_birth: formData.dob === "" ? null : formData.dob, // Convert empty string to null to prevent DB errors
      gender: formData.gender,
      qualification: formData.qualification,
      experience: formData.experience,
      currentAddress: formData.currentAddress,
      pincode: formData.pincode,
      area: formData.area,
      state: formData.state,
      city: formData.city,
      country: formData.country,
    }, {
      onSuccess: () => {
        onClose();
      }
    });
  };

  const inputClass = "rounded-xl !border-0 shadow-[0_4px_8px_-2px_rgba(0,0,0,0.25)] ring-1 ring-inset ring-gray-100 h-11 bg-white font-medium text-gray-700 placeholder:font-normal";
  const selectClass = "flex h-11 w-full rounded-xl border-0 shadow-[0_4px_8px_-2px_rgba(0,0,0,0.25)] ring-1 ring-inset ring-gray-100 bg-white px-3 py-1 font-medium shadow-sm transition-colors focus-visible:outline-none text-gray-700 appearance-none";

  const maxDate = new Date();
  maxDate.setFullYear(maxDate.getFullYear() - 16);
  const maxDateString = maxDate.toISOString().split('T')[0];

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-[800px] w-full p-0 overflow-hidden bg-[#fafafa] rounded-2xl border-0 shadow-2xl max-h-[90vh] flex flex-col">
        
        {/* Header */}
        <div className="flex items-center justify-between p-6 pb-2">
          <DialogTitle className="text-xl font-bold text-gray-900">Basic Details</DialogTitle>
          {/* Note: Shadcn DialogContent provides its own close X icon automatically, so we don't render another one here. */}
        </div>

        {/* Scrollable Form Body */}
        <div className="px-6 pb-6 overflow-y-auto">
          <form id="basic-details-form" onSubmit={handleSubmit} className="flex flex-col gap-6">
            
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4 pt-4">
              {/* Full Name */}
              <div className="sm:col-span-2 space-y-1.5">
                <Label htmlFor="fullName" className="text-sm font-medium text-gray-800">Full Name</Label>
                <Input 
                  id="fullName" name="fullName" 
                  value={formData.fullName} onChange={handleChange} 
                  className={inputClass} placeholder="Sujit Ranjan Moharana" 
                />
              </div>

              {/* Job Title */}
              <div className="space-y-1.5">
                <Label htmlFor="jobTitle" className="text-sm font-medium text-gray-800">Job title</Label>
                <select
                  id="jobTitle" name="jobTitle"
                  value={formData.jobTitle} onChange={handleChange}
                  className={`${selectClass} bg-gray-100 cursor-not-allowed`}
                  disabled
                >
                  <option value="" disabled>Select a role</option>
                  {roles.map(r => (
                    <option key={r.id} value={r.id}>{r.name}</option>
                  ))}
                </select>
              </div>

              {/* Phone Number */}
              <div className="space-y-1.5">
                <Label htmlFor="phone" className="text-sm font-medium text-gray-800">Phone Number</Label>
                <Input 
                  id="phone" name="phone" 
                  value={formData.phone} onChange={handleChange} 
                  className={`${inputClass} bg-gray-100 cursor-not-allowed`} placeholder="Phone Number" 
                  disabled
                />
              </div>

              {/* Email */}
              <div className="sm:col-span-2 space-y-1.5">
                <Label htmlFor="email" className="text-sm font-medium text-gray-800">Email</Label>
                <Input 
                  id="email" name="email" type="email"
                  value={formData.email} onChange={handleChange} 
                  className={`${inputClass} bg-gray-100 cursor-not-allowed`} placeholder="@gmail.com" 
                  disabled
                />
              </div>

              {/* DOB */}
              <div className="space-y-1.5">
                <Label htmlFor="dob" className="text-sm font-medium text-gray-800">DOB</Label>
                <Input 
                  id="dob" name="dob" type="date"
                  value={formData.dob} onChange={handleChange} 
                  max={maxDateString}
                  className={inputClass} 
                />
              </div>

              {/* Gender */}
              <div className="space-y-1.5">
                <Label className="text-sm font-medium text-gray-800">Gender</Label>
                <div className="flex items-center gap-3">
                  {['Male', 'Female', 'Other'].map((g) => {
                    const isSelected = formData.gender === g || (g.toLowerCase() === 'female' && formData.gender?.toLowerCase() === 'female');
                    return (
                      <button
                        key={g}
                        type="button"
                        onClick={() => setGender(g)}
                        className={`flex-1 h-11 rounded-xl text-sm font-medium transition-colors shadow-[0_4px_8px_-2px_rgba(0,0,0,0.25)] ring-1 ring-inset ${
                          isSelected
                            ? 'ring-[#ff6b00] text-[#ff6b00] bg-white'
                            : 'ring-gray-100 text-gray-500 bg-white hover:bg-gray-50'
                        }`}
                      >
                        {g}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Highest Qualification */}
              <div className="space-y-1.5">
                <Label htmlFor="qualification" className="text-sm font-medium text-gray-800">Highest Qualification</Label>
                <select 
                  id="qualification" name="qualification" 
                  value={formData.qualification} onChange={handleChange}
                  className={selectClass}
                  style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                >
                  <option value="" disabled>Select Highest Qualification</option>
                  {educationLevels.map(edu => (
                    <option key={edu.id} value={edu.name}>{edu.name}</option>
                  ))}
                </select>
              </div>

              {/* Experience */}
              <div className="space-y-1.5">
                <Label htmlFor="experience" className="text-sm font-medium text-gray-800">Experience</Label>
                <select 
                  id="experience" name="experience" 
                  value={formData.experience} onChange={handleChange}
                  className={selectClass}
                  style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                >
                  <option value="" disabled>Select Experience</option>
                  {experiences.map(exp => (
                    <option key={exp.id} value={exp.level}>
                      {exp.level} {exp.duration ? `(${exp.duration})` : ''}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="mt-2 mb-0">
              <h3 className="text-lg font-bold text-gray-900">Address Details</h3>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
              {/* Current Address */}
              <div className="sm:col-span-2 space-y-1.5">
                <Label htmlFor="currentAddress" className="text-sm font-medium text-gray-800">Current Address</Label>
                <Input 
                  id="currentAddress" name="currentAddress" 
                  value={formData.currentAddress} onChange={handleChange} 
                  className={inputClass} placeholder="Enter your address" 
                />
              </div>

              {/* Pincode */}
              <div className="space-y-1.5">
                <Label htmlFor="pincode" className="text-sm font-medium text-gray-800">Pincode</Label>
                <Input 
                  id="pincode" name="pincode" 
                  value={formData.pincode} onChange={handleChange} 
                  className={inputClass} placeholder="3435345" 
                />
              </div>

              {/* Area */}
              <div className="space-y-1.5">
                <Label htmlFor="area" className="text-sm font-medium text-gray-800">Area</Label>
                {pincodeAreas.length > 0 ? (
                  <select
                    id="area" name="area"
                    value={formData.area} onChange={(e) => {
                      handleChange(e);
                      const selected = pincodeAreas.find(a => a.area === e.target.value);
                      if (selected) {
                        setFormData(prev => ({
                          ...prev,
                          city: selected.city_name || prev.city,
                          state: selected.state_name || prev.state,
                          country: selected.country_name || prev.country,
                        }));
                      }
                    }}
                    className={selectClass}
                    style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                  >
                    {pincodeAreas.map((a, i) => <option key={i} value={a.area}>{a.area}</option>)}
                  </select>
                ) : (
                  <Input 
                    id="area" name="area" 
                    value={formData.area} onChange={handleChange} 
                    className={inputClass} placeholder="vdfvdfd" 
                  />
                )}
              </div>

              {/* State */}
              <div className="space-y-1.5">
                <Label htmlFor="state" className="text-sm font-medium text-gray-800">State</Label>
                {pincodeAreas.length > 0 ? (
                  <select
                    id="state" name="state"
                    value={formData.state} onChange={handleChange}
                    className={selectClass}
                    style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                  >
                    {Array.from(new Set(pincodeAreas.map(a => a.state_name).filter(Boolean))).map((state, i) => (
                      <option key={i} value={state as string}>{state as string}</option>
                    ))}
                  </select>
                ) : (
                  <Input 
                    id="state" name="state" 
                    value={formData.state} onChange={handleChange} 
                    className={inputClass} placeholder="Odisha" 
                  />
                )}
              </div>

              {/* City */}
              <div className="space-y-1.5">
                <Label htmlFor="city" className="text-sm font-medium text-gray-800">City</Label>
                {pincodeAreas.length > 0 ? (
                  <select
                    id="city" name="city"
                    value={formData.city} onChange={handleChange}
                    className={selectClass}
                    style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                  >
                    {Array.from(new Set(pincodeAreas.map(a => a.city_name).filter(Boolean))).map((city, i) => (
                      <option key={i} value={city as string}>{city as string}</option>
                    ))}
                  </select>
                ) : (
                  <Input 
                    id="city" name="city" 
                    value={formData.city} onChange={handleChange} 
                    className={inputClass} placeholder="Bbsr" 
                  />
                )}
              </div>

              {/* Country */}
              <div className="space-y-1.5">
                <Label htmlFor="country" className="text-sm font-medium text-gray-800">Country</Label>
                {pincodeAreas.length > 0 ? (
                  <select
                    id="country" name="country"
                    value={formData.country} onChange={handleChange}
                    className={selectClass}
                    style={{ backgroundImage: `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 0.75rem center', backgroundSize: '16px 16px', paddingRight: '2.5rem' }}
                  >
                    {Array.from(new Set(pincodeAreas.map(a => a.country_name).filter(Boolean))).map((country, i) => (
                      <option key={i} value={country as string}>{country as string}</option>
                    ))}
                  </select>
                ) : (
                  <Input 
                    id="country" name="country" 
                    value={formData.country} onChange={handleChange} 
                    className={inputClass} placeholder="India" 
                  />
                )}
              </div>
            </div>
          </form>
        </div>

        {/* Footer (Sticky) */}
        <div className="flex items-center justify-end gap-4 p-6 pt-4 bg-[#fafafa]">
          <button type="button" onClick={onClose} className="text-sm font-bold text-gray-900 hover:text-gray-700 px-2 py-2">
            Cancel
          </button>
          <Button type="submit" form="basic-details-form" className="bg-[#ff6b00] hover:bg-[#e65c00] text-white px-8 h-10 rounded-lg font-bold border-0 shadow-sm">
            Save
          </Button>
        </div>

      </DialogContent>
    </Dialog>
  );
}
