import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useAddEducation, useUpdateEducation, useDeleteEducation } from "@/hooks/useProfile";
import { Trash2, X } from "lucide-react";

interface EditEducationModalProps {
  isOpen: boolean;
  onClose: () => void;
  education?: any;
  existingEducations?: any[];
}

const levels = ["10th", "12th", "ITI", "Diploma", "Graduation", "Masters / Post-Graduation", "Doctorate / Phd"];
const educationTypes = ["Full-time", "Part-time", "Correspondence"];

const boards = ["CBSE", "ICSE", "State Board", "IB", "IGCSE", "Other"];
const mediums = ["English", "Hindi", "Regional Language", "Other"];
const gradingSystems = ["Scale 10 Grading System", "Scale 4 Grading System", "% Marks of 100 Maximum", "Course Requires a Pass"];

const courses = {
  Graduation: ["B.Tech / B.E.", "B.Ed", "B.Pharma", "BHM / BHMCT", "B.Sc", "B.Com", "B.A"],
  "Masters / Post-Graduation": ["M.Des.", "DM", "MDS", "M.Tech", "MBA", "M.Sc", "M.A"],
  "Doctorate / Phd": ["Ph.D", "M.Phil"],
  Diploma: ["Polytechnic", "PG Diploma"],
  ITI: ["Fitter", "Electrician", "Welder", "Mechanic"]
};

export function EditEducationModal({ isOpen, onClose, education, existingEducations = [] }: EditEducationModalProps) {
  const addMutation = useAddEducation();
  const updateMutation = useUpdateEducation();
  const deleteMutation = useDeleteEducation();

  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const [formData, setFormData] = useState({
    level_of_education: "",
    examination_board: "",
    medium_of_study: "",
    grading_system: "",
    marks: "",
    degree: "",
    institute_name: "",
    specialization: "",
    education_type: "",
    start_year: "",
    end_year: "",
  });

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

  useEffect(() => {
    if (isOpen) {
      if (education) {
        setFormData({
          level_of_education: education.level_of_education || "",
          examination_board: education.examination_board || "",
          medium_of_study: education.medium_of_study || "",
          grading_system: education.grading_system || "",
          marks: education.marks || "",
          degree: education.degree || education.degree_name || "",
          institute_name: education.institute_name || education.institution_name || "",
          specialization: education.specialization || education.field_of_study || "",
          education_type: education.education_type || "",
          start_year: education.start_year?.toString() || "",
          end_year: education.end_year?.toString() || "",
        });
      } else {
        setFormData({
          level_of_education: "",
          examination_board: "",
          medium_of_study: "",
          grading_system: "",
          marks: "",
          degree: "",
          institute_name: "",
          specialization: "",
          education_type: "",
          start_year: "",
          end_year: "",
        });
      }
    }
  }, [isOpen, education]);

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

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const data = {
      ...formData,
      start_year: formData.start_year ? parseInt(formData.start_year) : null,
      end_year: formData.end_year ? parseInt(formData.end_year) : null,
    };

    // Clean up fields based on level_of_education before saving
    if (isSchoolLevel) {
      data.degree = "";
      data.specialization = "";
      data.education_type = "";
      data.start_year = null;
      data.grading_system = "";
    } else {
      data.examination_board = "";
      data.medium_of_study = "";
    }

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

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

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

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

  const labelClass = "text-[14px] font-semibold text-gray-800 mb-2 block";
  const inputClass = "w-full rounded-xl border border-gray-200 h-11 bg-white px-4 text-gray-700 text-[14px] focus:outline-none focus:border-[#ff6b00]";
  const selectClass = "w-full rounded-xl border border-gray-200 h-11 bg-white px-4 text-gray-700 text-[14px] focus:outline-none focus:border-[#ff6b00] appearance-none";

  const isSchoolLevel = formData.level_of_education === "10th" || formData.level_of_education === "12th";
  const hasSelectedLevel = formData.level_of_education !== "";

  // Get courses based on level
  const levelKey = formData.level_of_education as keyof typeof courses;
  const availableCourses = courses[levelKey] || courses["Graduation"];

  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">
            {education ? 'Edit Education' : 'Add Education'}
          </h2>
          <div className="flex items-center gap-4">
            {education && (
              <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="education-form" onSubmit={handleSubmit} className="flex flex-col gap-8">
            
            {/* 1. LEVEL OF EDUCATION */}
            <div>
              <label className={labelClass}>Your completed level of education</label>
              <div className="flex flex-wrap gap-3 mt-2">
                {levels.map((lvl) => {
                  const isSingleEntryType = lvl === "10th" || lvl === "12th";
                  const alreadyExists = isSingleEntryType && existingEducations.some(e => e.level_of_education === lvl);
                  const isCurrentlyEditingThis = education?.level_of_education === lvl;
                  const disabled = alreadyExists && !isCurrentlyEditingThis;

                  return (
                    <button
                      key={lvl}
                      type="button"
                      disabled={disabled}
                      onClick={() => handlePillSelect('level_of_education', lvl)}
                      className={`px-5 py-2.5 rounded-full text-[14px] font-medium transition-all border ${
                        formData.level_of_education === lvl
                          ? 'border-[#ff6b00] bg-[#fff2ed] text-[#ff6b00]'
                          : disabled
                            ? 'border-gray-200 bg-gray-50 text-gray-400 opacity-50 cursor-not-allowed'
                            : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                      }`}
                    >
                      {lvl}
                    </button>
                  );
                })}
              </div>
            </div>

            {hasSelectedLevel && (
              <div className="bg-[#fcf8f6] p-4 rounded-xl border border-orange-100 flex items-start gap-3">
                <div className="text-orange-500 mt-0.5">💡</div>
                <p className="text-[13px] text-gray-700 leading-relaxed">
                  Adding your educational details help recruiters know your value as a potential candidate.
                </p>
              </div>
            )}

            {/* DYNAMIC FORM SECTION */}
            {hasSelectedLevel && (
              <div className="flex flex-col gap-8 animate-in fade-in slide-in-from-bottom-4 duration-300">
                
                {isSchoolLevel ? (
                  <>
                    {/* 10TH / 12TH VIEW */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      <div>
                        <label className={labelClass}>Examination board</label>
                        <div className="relative">
                          <select
                            name="examination_board"
                            value={formData.examination_board}
                            onChange={handleChange}
                            className={selectClass}
                            required
                          >
                            <option value="">Select Board Name</option>
                            {boards.map(b => <option key={b} value={b}>{b}</option>)}
                          </select>
                        </div>
                      </div>
                      
                      <div>
                        <label className={labelClass}>Medium of study</label>
                        <div className="relative">
                          <select
                            name="medium_of_study"
                            value={formData.medium_of_study}
                            onChange={handleChange}
                            className={selectClass}
                            required
                          >
                            <option value="">Select Medium</option>
                            {mediums.map(m => <option key={m} value={m}>{m}</option>)}
                          </select>
                        </div>
                      </div>
                    </div>

                    <div>
                      <label className={labelClass}>School Name</label>
                      <input
                        type="text"
                        name="institute_name"
                        value={formData.institute_name}
                        onChange={handleChange}
                        placeholder="Enter the name of your school"
                        className={inputClass}
                        required
                      />
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      <div>
                        <label className={labelClass}>Percentage</label>
                        <input
                          type="text"
                          name="marks"
                          value={formData.marks}
                          onChange={handleChange}
                          placeholder="e.g. 95"
                          className={inputClass}
                          required
                        />
                      </div>
                      
                      <div>
                        <label className={labelClass}>Passing year</label>
                        <div className="relative">
                          <select
                            name="end_year"
                            value={formData.end_year}
                            onChange={handleChange}
                            className={selectClass}
                            required
                          >
                            <option value="">YYYY</option>
                            {years.map(y => <option key={y} value={y}>{y}</option>)}
                          </select>
                        </div>
                      </div>
                    </div>
                  </>
                ) : (
                  <>
                    {/* GRADUATION / DIPLOMA / POST-GRAD VIEW */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      <div>
                        <label className={labelClass}>Course name</label>
                        <div className="relative">
                          <select
                            name="degree"
                            value={formData.degree}
                            onChange={handleChange}
                            className={selectClass}
                            required
                          >
                            <option value="">Select course from the list</option>
                            {availableCourses.map(c => <option key={c} value={c}>{c}</option>)}
                          </select>
                        </div>
                      </div>
                      
                      <div>
                        <label className={labelClass}>Specialization (Optional)</label>
                        <input
                          type="text"
                          name="specialization"
                          value={formData.specialization}
                          onChange={handleChange}
                          placeholder="e.g. Computer Science"
                          className={inputClass}
                        />
                      </div>
                    </div>

                    <div>
                      <label className={labelClass}>College name</label>
                      <input
                        type="text"
                        name="institute_name"
                        value={formData.institute_name}
                        onChange={handleChange}
                        placeholder="Enter the name of your college"
                        className={inputClass}
                        required
                      />
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      <div>
                        <label className={labelClass}>Grading system</label>
                        <div className="relative">
                          <select
                            name="grading_system"
                            value={formData.grading_system}
                            onChange={handleChange}
                            className={selectClass}
                            required
                          >
                            <option value="">Select grading system</option>
                            {gradingSystems.map(g => <option key={g} value={g}>{g}</option>)}
                          </select>
                        </div>
                      </div>
                      
                      <div>
                        <label className={labelClass}>Marks / Score</label>
                        <input
                          type="text"
                          name="marks"
                          value={formData.marks}
                          onChange={handleChange}
                          placeholder={formData.grading_system.includes("10") ? "e.g. 8.5" : "e.g. 85"}
                          className={inputClass}
                          required
                        />
                      </div>
                    </div>

                    {/* Course Duration */}
                    <div>
                      <label className={labelClass}>Course duration</label>
                      <div className="flex items-center gap-4 mt-2">
                        <div className="flex-1 relative">
                          <select name="start_year" value={formData.start_year} onChange={handleChange} className={selectClass} required>
                            <option value="">Starting year</option>
                            {years.map(y => <option key={y} value={y}>{y}</option>)}
                          </select>
                        </div>
                        <span className="text-gray-500 font-medium text-sm">to</span>
                        <div className="flex-1 relative">
                          <select name="end_year" value={formData.end_year} onChange={handleChange} className={selectClass} required>
                            <option value="">Ending year</option>
                            {years.map(y => <option key={y} value={y}>{y}</option>)}
                          </select>
                        </div>
                      </div>
                    </div>

                    {/* Course Type */}
                    <div>
                      <label className={labelClass}>Course type</label>
                      <div className="flex flex-wrap gap-3 mt-2">
                        {educationTypes.map((type) => (
                          <button
                            key={type}
                            type="button"
                            onClick={() => handlePillSelect('education_type', type)}
                            className={`px-8 py-2.5 rounded-lg text-[14px] font-medium transition-all border ${
                              formData.education_type === type
                                ? 'border-[#ff6b00] bg-[#fff2ed] text-[#ff6b00]'
                                : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
                            }`}
                          >
                            {type}
                          </button>
                        ))}
                      </div>
                    </div>
                  </>
                )}
              </div>
            )}
          </form>
        </div>

        <div className="flex items-center justify-end p-6 pt-4 border-t border-gray-100 bg-white">
          <div className="flex items-center gap-4">
            <button type="button" onClick={onClose} className="text-[15px] font-semibold text-gray-700 hover:text-gray-900 px-4 py-2">
              Cancel
            </button>
            <Button
              form="education-form"
              type="submit"
              disabled={!hasSelectedLevel}
              className="bg-[#ff6b00] hover:bg-[#e65c00] text-white px-8 h-12 rounded-xl font-semibold shadow-sm min-w-[140px] text-[15px] disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Save
            </Button>
          </div>
        </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 Education?</h3>
              <p className="text-gray-500 mb-8">
                Are you sure you want to delete this education entry? 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>
  );
}
