import { useState, useEffect } from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useAddExperience, useUpdateExperience, useDeleteExperience } from "@/hooks/useProfile";
import { api } from "@/services/api";
import { Search, ChevronDown, Trash2, X } from "lucide-react";

interface EditWorkExperienceModalProps {
  isOpen: boolean;
  onClose: () => void;
  experience?: any; // null if adding new
}

export function EditWorkExperienceModal({ isOpen, onClose, experience }: EditWorkExperienceModalProps) {
  const addMutation = useAddExperience();
  const updateMutation = useUpdateExperience();
  const deleteMutation = useDeleteExperience();

  const [roles, setRoles] = useState<any[]>([]);
  const [jobTypes, setJobTypes] = useState<any[]>([]);
  const [allSkills, setAllSkills] = useState<any[]>([]);

  const [searchRoleQuery, setSearchRoleQuery] = useState("");
  const [isRoleDropdownOpen, setIsRoleDropdownOpen] = useState(false);
  
  const [searchSkillQuery, setSearchSkillQuery] = useState("");
  const [isSkillDropdownOpen, setIsSkillDropdownOpen] = useState(false);

  const [startMonth, setStartMonth] = useState("");
  const [startYear, setStartYear] = useState("");
  const [endMonth, setEndMonth] = useState("");
  const [endYear, setEndYear] = useState("");
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const [formData, setFormData] = useState({
    company: "",
    designation: "",
    department: "",
    employment_type_id: "",
    current: false,
    responsibilities: "",
    skills: [] as any[], // array of full skill objects {id, name}
    notice_period: "No notice period",
  });

  const months = [
    { value: "01", label: "Jan" }, { value: "02", label: "Feb" }, { value: "03", label: "Mar" },
    { value: "04", label: "Apr" }, { value: "05", label: "May" }, { value: "06", label: "Jun" },
    { value: "07", label: "Jul" }, { value: "08", label: "Aug" }, { value: "09", label: "Sep" },
    { value: "10", label: "Oct" }, { value: "11", label: "Nov" }, { value: "12", label: "Dec" }
  ];

  const currentYear = new Date().getFullYear();
  const years = Array.from({ length: 50 }, (_, i) => (currentYear - i).toString());

  useEffect(() => {
    if (isOpen) {
      api.get('/roles').then(res => setRoles(res.data || [])).catch(console.error);
      api.get('/job_type').then(res => setJobTypes(res.data || [])).catch(console.error);
      
      let skillsData: any[] = [];
      api.get('/skills').then(res => {
        skillsData = res.data || [];
        setAllSkills(skillsData);
        
        if (experience && Array.isArray(experience.skills)) {
          if (experience.skills.length > 0 && typeof experience.skills[0] === 'number') {
            const mappedSkills = experience.skills.map((id: number) => skillsData.find((s: any) => s.id === id)).filter(Boolean);
            setFormData(prev => ({ ...prev, skills: mappedSkills }));
          }
        }
      }).catch(console.error);

      if (experience) {
        setFormData(prev => ({
          ...prev,
          company: experience.company || experience.company_name || "",
          designation: experience.designation || experience.job_title || "",
          department: experience.department || "",
          employment_type_id: experience.employment_type_id?.toString() || "",
          current: experience.current || false,
          current: experience.current ? true : false,
          responsibilities: experience.responsibilities || experience.description || "",
          skills: Array.isArray(experience.skills) && typeof experience.skills[0] !== 'number' ? experience.skills : prev.skills,
          notice_period: experience.notice_period || "No notice period",
        }));
        setSearchRoleQuery(experience.designation || experience.job_title || "");

        if (experience.start_date) {
          const date = new Date(experience.start_date);
          setStartMonth(String(date.getMonth() + 1).padStart(2, '0'));
          setStartYear(String(date.getFullYear()));
        }
        if (experience.end_date) {
          const date = new Date(experience.end_date);
          setEndMonth(String(date.getMonth() + 1).padStart(2, '0'));
          setEndYear(String(date.getFullYear()));
        }
      } else {
        setFormData({
          company: "",
          designation: "",
          department: "",
          employment_type_id: "",
          current: false,
          responsibilities: "",
          skills: [],
          notice_period: "No notice period",
        });
        setSearchRoleQuery("");
        setStartMonth("");
        setStartYear("");
        setEndMonth("");
        setEndYear("");
      }
    }
  }, [isOpen, experience]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    if (type === 'checkbox') {
      const checked = (e.target as HTMLInputElement).checked;
      setFormData(prev => ({ ...prev, [name]: checked }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  const handleAddSkill = (skill: any) => {
    if (formData.skills.length >= 10) return;
    if (!formData.skills.some(s => s.id === skill.id)) {
      setFormData(prev => ({ ...prev, skills: [...prev.skills, skill] }));
    }
    setSearchSkillQuery("");
    setIsSkillDropdownOpen(false);
  };

  const handleRemoveSkill = (skillId: number) => {
    setFormData(prev => ({ ...prev, skills: prev.skills.filter(s => s.id !== skillId) }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const data = {
      company: formData.company,
      designation: formData.designation,
      department: formData.department,
      employment_type_id: formData.employment_type_id ? Number(formData.employment_type_id) : null,
      start_date: startYear && startMonth ? `${startYear}-${startMonth}-01` : null,
      end_date: formData.current || !endYear || !endMonth ? null : `${endYear}-${endMonth}-01`,
      current: formData.current,
      responsibilities: formData.responsibilities,
      skills: formData.skills.map(s => s.id),
      notice_period: formData.current ? formData.notice_period : null,
    };

    if (experience?.id) {
      updateMutation.mutate({ id: experience.id, data }, { onSuccess: onClose });
    } else {
      addMutation.mutate(data, { onSuccess: onClose });
    }
  };

  const handleDeleteClick = () => {
    setIsDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (experience?.id) {
      deleteMutation.mutate(experience.id, { onSuccess: onClose });
    }
  };

  const cancelDelete = () => {
    setIsDeleteDialogOpen(false);
  };

  const filteredRoles = roles.filter(r => r.name?.toLowerCase().includes(searchRoleQuery.toLowerCase()));
  const filteredSkills = allSkills.filter(s => s.skill_name?.toLowerCase().includes(searchSkillQuery.toLowerCase()) && !formData.skills.some(sel => sel.id === s.id));
  
  const labelClass = "text-[15px] font-semibold text-gray-900 mb-2 block";
  const inputClass = "w-full rounded-xl border border-gray-200 h-12 bg-white px-4 text-gray-700 text-[15px] focus:outline-none focus:border-[#ff6b00]";
  const sectionTitleClass = "text-xl font-bold text-gray-900 mb-6";

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent showCloseButton={false} className="sm:max-w-[700px] w-full max-h-[90vh] p-0 overflow-hidden bg-white rounded-2xl border-0 shadow-2xl flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 pb-2">
          <h2 className="text-2xl font-bold text-gray-900">
            Edit Experience
          </h2>
          <div className="flex items-center gap-4">
            {experience && (
              <button type="button" onClick={handleDeleteClick} className="text-red-500 hover:text-red-600 transition-colors">
                <Trash2 className="w-5 h-5" />
              </button>
            )}
            <button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-600 transition-colors">
              <X className="w-6 h-6" />
            </button>
          </div>
        </div>

        <div className="p-8 pt-6 flex-1 overflow-y-auto">
          <form id="experience-form" onSubmit={handleSubmit} className="flex flex-col gap-10">
            
            <div>
              <h3 className={sectionTitleClass}>Job Details</h3>
              <div className="flex flex-col gap-6">
                
                <div className="relative">
                  <label className={labelClass}>Job Title</label>
                  <div className="relative">
                    <input 
                      type="text"
                      placeholder="e.g. Flutter Developer"
                      value={searchRoleQuery}
                      onChange={(e) => {
                        setSearchRoleQuery(e.target.value);
                        setIsRoleDropdownOpen(true);
                        setFormData(prev => ({ ...prev, designation: e.target.value }));
                      }}
                      onClick={() => setIsRoleDropdownOpen(true)}
                      className={inputClass}
                      required
                    />
                    <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                    {isRoleDropdownOpen && filteredRoles.length > 0 && (
                      <div className="absolute z-10 w-full mt-2 bg-white rounded-xl shadow-lg border border-gray-100 max-h-48 overflow-y-auto">
                        {filteredRoles.map(role => (
                          <div
                            key={role.id}
                            onClick={() => {
                              setSearchRoleQuery(role.name);
                              setFormData(prev => ({ ...prev, designation: role.name }));
                              setIsRoleDropdownOpen(false);
                            }}
                            className="px-4 py-3 hover:bg-gray-50 cursor-pointer text-[15px] font-medium text-gray-700 border-b border-gray-50 last:border-0"
                          >
                            {role.name}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>

                <div>
                  <label className={labelClass}>Job Role</label>
                  <div className="relative">
                    <input 
                      name="department" 
                      value={formData.department} 
                      onChange={handleChange} 
                      placeholder="e.g. Software applications" 
                      className={inputClass} 
                    />
                    <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                  </div>
                </div>

                <div>
                  <label className={labelClass}>Description</label>
                  <div className="relative">
                    <textarea 
                      name="responsibilities" 
                      placeholder="Enter description..." 
                      value={formData.responsibilities} 
                      onChange={handleChange} 
                      rows={4} 
                      maxLength={2000}
                      className="w-full rounded-xl border border-gray-200 bg-white p-4 text-[15px] text-gray-700 focus:outline-none focus:border-[#ff6b00]" 
                    />
                    <div className="absolute bottom-4 right-4 text-xs text-gray-400">
                      {formData.responsibilities.length}/2000
                    </div>
                  </div>
                </div>

                <div>
                  <label className={labelClass}>Skills (up to 10)</label>
                  <div className="relative">
                    <input 
                      type="text"
                      placeholder="Search skill"
                      value={searchSkillQuery}
                      onChange={(e) => {
                        setSearchSkillQuery(e.target.value);
                        setIsSkillDropdownOpen(true);
                      }}
                      onClick={() => setIsSkillDropdownOpen(true)}
                      disabled={formData.skills.length >= 10}
                      className={`${inputClass} pl-10`}
                    />
                    <Search className="w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                    
                    {isSkillDropdownOpen && filteredSkills.length > 0 && (
                      <div className="absolute z-10 w-full mt-2 bg-white rounded-xl shadow-lg border border-gray-100 max-h-48 overflow-y-auto">
                        {filteredSkills.map(skill => (
                          <div
                            key={skill.id}
                            onClick={() => handleAddSkill(skill)}
                            className="px-4 py-3 hover:bg-gray-50 cursor-pointer text-[15px] font-medium text-gray-700 border-b border-gray-50 last:border-0"
                          >
                            {skill.skill_name}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                  
                  <div className="flex flex-wrap gap-3 mt-4">
                    {formData.skills.map((skill: any) => (
                      <div key={skill.id} className="flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#ff6b00] text-[#ff6b00] bg-white text-[15px] font-medium">
                        <span>{skill.skill_name || skill.name}</span>
                        <button type="button" onClick={() => handleRemoveSkill(skill.id)} className="hover:opacity-70 transition-opacity flex items-center justify-center pt-0.5">
                          <X className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

              </div>
            </div>

            <div className="h-px bg-gray-100 -mx-8 w-[calc(100%+4rem)]" />

            <div>
              <h3 className={sectionTitleClass}>Company Details</h3>
              <div>
                <label className={labelClass}>Company Name</label>
                <input 
                  name="company" 
                  value={formData.company} 
                  onChange={handleChange} 
                  required 
                  className={inputClass} 
                  placeholder="e.g. ABCDFVGG Solution Pvt.Ltd"
                />
              </div>
            </div>

            <div className="h-px bg-gray-100 -mx-8 w-[calc(100%+4rem)]" />

            <div>
              <h3 className={sectionTitleClass}>Employment Details</h3>
              <div className="flex flex-col gap-8">
                
                <div>
                  <label className={labelClass}>Are you currently working in this company?</label>
                  <div className="flex gap-4">
                    <button
                      type="button"
                      onClick={() => setFormData(prev => ({ ...prev, current: true }))}
                      className={`h-11 px-8 rounded-xl font-medium transition-colors flex-1 sm:flex-none ${
                        formData.current 
                          ? 'border border-[#ff6b00] text-[#ff6b00] bg-white' 
                          : 'border border-gray-200 text-gray-500 bg-gray-50 hover:bg-gray-100'
                      }`}
                    >
                      Yes
                    </button>
                    <button
                      type="button"
                      onClick={() => setFormData(prev => ({ ...prev, current: false }))}
                      className={`h-11 px-8 rounded-xl font-medium transition-colors flex-1 sm:flex-none ${
                        !formData.current 
                          ? 'border border-[#ff6b00] text-[#ff6b00] bg-white' 
                          : 'border border-gray-200 text-gray-500 bg-gray-50 hover:bg-gray-100'
                      }`}
                    >
                      No
                    </button>
                  </div>
                </div>

                <div>
                  <label className={labelClass}>Employment Type</label>
                  <div className="flex flex-wrap gap-4">
                    {jobTypes.map(type => {
                      const isSelected = String(formData.employment_type_id) === String(type.id);
                      return (
                        <button
                          key={type.id}
                          type="button"
                          onClick={() => setFormData(prev => ({ ...prev, employment_type_id: String(type.id) }))}
                          className={`h-11 px-8 rounded-xl font-medium transition-colors ${
                            isSelected
                              ? 'border border-[#ff6b00] text-[#ff6b00] bg-white' 
                              : 'border border-gray-200 text-gray-500 bg-white hover:bg-gray-50'
                          }`}
                        >
                          {type.name || type.title}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div>
                  <label className={labelClass}>Experience in this company</label>
                  
                  <div className="flex flex-col gap-4 mt-2">
                    <div className="grid grid-cols-[60px_1fr_1fr] items-center gap-4">
                      <span className="text-gray-500 text-[15px]">Start</span>
                      <div className="relative">
                        <select 
                          value={startMonth} 
                          onChange={(e) => setStartMonth(e.target.value)} 
                          required
                          className={`${inputClass} appearance-none cursor-pointer`}
                        >
                          <option value="" disabled>Month</option>
                          {months.map(m => (
                            <option key={m.value} value={m.value}>{m.label}</option>
                          ))}
                        </select>
                        <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                      </div>
                      <div className="relative">
                        <select 
                          value={startYear} 
                          onChange={(e) => setStartYear(e.target.value)} 
                          required
                          className={`${inputClass} appearance-none cursor-pointer`}
                        >
                          <option value="" disabled>Year</option>
                          {years.map(y => (
                            <option key={y} value={y}>{y}</option>
                          ))}
                        </select>
                        <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                      </div>
                    </div>

                    {!formData.current && (
                      <div className="grid grid-cols-[60px_1fr_1fr] items-center gap-4">
                        <span className="text-gray-500 text-[15px]">End</span>
                        <div className="relative">
                          <select 
                            value={endMonth} 
                            onChange={(e) => setEndMonth(e.target.value)} 
                            required={!formData.current}
                            className={`${inputClass} appearance-none cursor-pointer`}
                          >
                            <option value="" disabled>Month</option>
                            {months.map(m => (
                              <option key={m.value} value={m.value}>{m.label}</option>
                            ))}
                          </select>
                          <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                        </div>
                        <div className="relative">
                          <select 
                            value={endYear} 
                            onChange={(e) => setEndYear(e.target.value)} 
                            required={!formData.current}
                            className={`${inputClass} appearance-none cursor-pointer`}
                          >
                            <option value="" disabled>Year</option>
                            {years.map(y => (
                              <option key={y} value={y}>{y}</option>
                            ))}
                          </select>
                          <ChevronDown className="w-5 h-5 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none" />
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {formData.current && (
                  <div>
                    <label className={labelClass}>Notice Period</label>
                    <div className="flex flex-wrap gap-3 mt-2">
                      {[
                        "No notice period",
                        "Less than 15 days",
                        "1 month",
                        "2 months",
                        "3 or more months"
                      ].map((np) => {
                        const isSelected = formData.notice_period === np;
                        return (
                          <button
                            key={np}
                            type="button"
                            onClick={() => setFormData(prev => ({ ...prev, notice_period: np }))}
                            className={`h-11 px-6 sm:px-8 rounded-xl font-medium transition-colors ${
                              isSelected
                                ? 'border border-[#ff6b00] text-[#ff6b00] bg-white' 
                                : 'border border-gray-200 text-gray-500 bg-white hover:bg-gray-50'
                            }`}
                          >
                            {np}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                )}

              </div>
            </div>

          </form>
          <div className="h-6"></div>
        </div>

        <div className="flex items-center justify-end p-6 border-t border-gray-100 gap-6">
          <button type="button" onClick={onClose} className="font-bold text-gray-900 hover:text-gray-700 text-[15px]">
            Cancel
          </button>
          <Button form="experience-form" type="submit" className="bg-[#ff6b00] hover:bg-[#e65c00] text-white px-10 h-11 rounded-lg font-bold border-0 shadow-sm">
            Save
          </Button>
        </div>

        {/* Delete Confirmation Overlay */}
        {isDeleteDialogOpen && (
          <div className="absolute inset-0 bg-white/90 backdrop-blur-sm z-50 flex items-center justify-center p-6 rounded-2xl">
            <div className="bg-white rounded-2xl shadow-xl border border-gray-100 p-8 max-w-sm w-full text-center">
              <div className="w-16 h-16 bg-red-50 rounded-full flex items-center justify-center mx-auto mb-6">
                <Trash2 className="w-8 h-8 text-red-500" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">Delete Experience?</h3>
              <p className="text-gray-500 mb-8">
                Are you sure you want to delete this work experience? This action cannot be undone.
              </p>
              <div className="flex gap-4">
                <button
                  type="button"
                  onClick={cancelDelete}
                  className="flex-1 py-3 px-4 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={confirmDelete}
                  className="flex-1 py-3 px-4 bg-red-500 hover:bg-red-600 text-white font-semibold rounded-xl transition-colors"
                  disabled={deleteMutation.isPending}
                >
                  {deleteMutation.isPending ? 'Deleting...' : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
