import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { FaTimes, FaSave, FaSpinner } from "react-icons/fa";
import {
  getPersistedFormData,
  saveFormData,
  clearPersistedFormData,
  shouldPersistFormData,
} from "../../utils/formPersistence";

// Helper function to get current user ID
const getCurrentUserId = () => {
  try {
    const user = JSON.parse(localStorage.getItem("user"));
    return user ? user.user_id : 201; // Default to 201 if no user found
  } catch (error) {
    console.error("Error getting current user:", error);
    return 201; // Default fallback
  }
};

const EditProjectModal = ({
  isOpen,
  onClose,
  project,
  projectTypes,
  projectStatuses,
  projectPriorities,
  poStatuses,
  invoiceStatuses,
  employees,
  divisions,
  onSave,
  loading,
}) => {
  const { isLight } = useTheme();
  const [formData, setFormData] = useState({
    project_id: "",
    project_name: "",
    project_lead_emp_id: "",
    type_id: "",
    status_id: "",
    invoice_status_id: "",
    priority_level_id: "",
    project_start_date: "",
    deadline: "",
    percent_completed: "",
    estimated_hours: "",
    actual_hours: "",
    remarks: "",
    division_id: "",
  });
  const [errors, setErrors] = useState({});

  // Load persisted form data when modal opens
  useEffect(() => {
    if (isOpen && project) {
      const persistedData = getPersistedFormData(
        "editProject",
        project.project_id
      );
      if (persistedData) {
        console.log("Loading persisted data:", persistedData);
        setFormData(persistedData);
      } else {
        console.log("No persisted data found for project:", project.project_id);
      }
    }
  }, [isOpen, project]);

  // Save form data whenever it changes
  useEffect(() => {
    if (isOpen && project && shouldPersistFormData(formData)) {
      console.log("Saving form data:", formData);
      saveFormData("editProject", formData, project.project_id);
    }
  }, [formData, isOpen, project]);

  // Debug: Log form data changes
  useEffect(() => {
    if (isOpen && project) {
      console.log("Current form data:", formData);
    }
  }, [formData, isOpen, project]);

  // Populate form when project changes
  useEffect(() => {
    if (project) {
      console.log("Project data received:", project);
      const persistedData = getPersistedFormData(
        "editProject",
        project.project_id
      );
      if (persistedData) {
        console.log("Loading persisted data:", persistedData);
        setFormData(persistedData);
      } else {
        console.log("No persisted data found for project:", project.project_id);

        // Find the correct IDs by matching the text values
        const findTypeId = () => {
          const type = projectTypes.find(
            (t) => t.type_name === project.type_name
          );
          return type ? type.type_id.toString() : "";
        };

        const findStatusId = () => {
          const status = projectStatuses.find(
            (s) => s.status_name === project.status_name
          );
          return status ? status.status_id.toString() : "";
        };

        const findPriorityId = () => {
          const priority = projectPriorities.find(
            (p) => p.priority_level_name === project.priority_level_name
          );
          return priority ? priority.priority_level_id.toString() : "";
        };

        const findInvoiceStatusId = () => {
          const invoice = invoiceStatuses.find(
            (i) => i.invoice_status_name === project.invoice_status_name
          );
          return invoice ? invoice.invoice_status_id.toString() : "";
        };

        const findEmployeeId = () => {
          const employee = employees.find(
            (e) => e.employee_name === project.project_lead_name
          );
          return employee ? employee.employee_id.toString() : "";
        };

        const findDivisionId = () => {
          const division = divisions.find(
            (d) => d.division_name === project.division_name
          );
          return division ? division.division_id.toString() : "";
        };

        const initialFormData = {
          project_id: project.project_id || "",
          project_name: project.project_name || "",
          remarks: project.remarks || "",
          percent_completed: project.percent_completed || "",
          estimated_hours: project.estimated_hours || "",
          actual_hours: project.actual_hours || "",
          project_start_date: project.project_start_date
            ? project.project_start_date.split("T")[0]
            : "",
          deadline: project.deadline ? project.deadline.split("T")[0] : "",
          // Map text values to IDs
          type_id: findTypeId(),
          status_id: findStatusId(),
          priority_level_id: findPriorityId(),
          invoice_status_id: findInvoiceStatusId(),
          project_lead_emp_id: findEmployeeId(),
          division_id: findDivisionId(),
          po_status: project.po_status || "",
        };
        console.log("Setting initial form data:", initialFormData);
        setFormData((prev) => ({ ...prev, ...initialFormData }));
      }
      setErrors({});
    }
  }, [
    project,
    projectTypes,
    projectStatuses,
    projectPriorities,
    invoiceStatuses,
    employees,
    divisions,
  ]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    console.log(`Input changed - ${name}: ${value}`);
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  const validateForm = () => {
    const newErrors = {};

    if (!formData.project_name.trim()) {
      newErrors.project_name = "Project name is required";
    } else if (formData.project_name.trim().length < 2) {
      newErrors.project_name = "Project name must be at least 2 characters";
    }

    if (!formData.project_lead_emp_id) {
      newErrors.project_lead_emp_id = "Project lead is required";
    }

    if (!formData.type_id) {
      newErrors.type_id = "Project type is required";
    }

    if (!formData.status_id) {
      newErrors.status_id = "Project status is required";
    }

    if (!formData.invoice_status_id) {
      newErrors.invoice_status_id = "Invoice status is required";
    }

    if (!formData.priority_level_id) {
      newErrors.priority_level_id = "Priority level is required";
    }

    if (
      formData.percent_completed !== "" &&
      (isNaN(formData.percent_completed) ||
        formData.percent_completed < 0 ||
        formData.percent_completed > 100)
    ) {
      newErrors.percent_completed = "Progress must be between 0 and 100";
    }

    if (
      formData.estimated_hours !== "" &&
      (isNaN(formData.estimated_hours) || formData.estimated_hours < 0)
    ) {
      newErrors.estimated_hours = "Estimated hours must be a positive number";
    }

    if (
      formData.actual_hours !== "" &&
      (isNaN(formData.actual_hours) || formData.actual_hours < 0)
    ) {
      newErrors.actual_hours = "Actual hours must be a positive number";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }

    // Process form data to handle empty strings for numeric fields
    const processedData = {
      ...formData,
      // Convert empty strings to null for numeric fields
      percent_completed:
        formData.percent_completed === ""
          ? null
          : Number(formData.percent_completed),
      estimated_hours:
        formData.estimated_hours === ""
          ? null
          : Number(formData.estimated_hours),
      actual_hours:
        formData.actual_hours === "" ? null : Number(formData.actual_hours),
      // Convert empty strings to null for ID fields
      project_lead_emp_id:
        formData.project_lead_emp_id === ""
          ? null
          : Number(formData.project_lead_emp_id),
      type_id: formData.type_id === "" ? null : Number(formData.type_id),
      status_id: formData.status_id === "" ? null : Number(formData.status_id),
      invoice_status_id:
        formData.invoice_status_id === ""
          ? null
          : Number(formData.invoice_status_id),
      priority_level_id:
        formData.priority_level_id === ""
          ? null
          : Number(formData.priority_level_id),
      division_id:
        formData.division_id === "" ? null : Number(formData.division_id),
      user_id: getCurrentUserId(),
    };

    // Clear persisted data when form is submitted
    if (project) {
      clearPersistedFormData("editProject", project.project_id);
    }
    onSave(processedData);
  };

  // Reset form when modal closes
  useEffect(() => {
    if (!isOpen) {
      setFormData({
        project_id: "",
        project_name: "",
        project_lead_emp_id: "",
        type_id: "",
        status_id: "",
        invoice_status_id: "",
        priority_level_id: "",
        project_start_date: "",
        deadline: "",
        percent_completed: "",
        estimated_hours: "",
        actual_hours: "",
        remarks: "",
        division_id: "",
      });
      setErrors({});
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const modalBgClass = isLight ? "bg-white" : "bg-slate-800";

  const inputClass = isLight
    ? "bg-white text-gray-900 border-yellow-200 focus:ring-amber-500 focus:border-amber-500"
    : "bg-slate-700 text-slate-100 border-slate-600 focus:ring-cyan-400 focus:border-cyan-400 hover:border-slate-500";

  const buttonClass = isLight
    ? "bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
    : "bg-blue-600 hover:bg-blue-700 text-white shadow-lg";

  const textClass = isLight ? "text-amber-700" : "text-slate-300";

  // Filter out directors from employees (role_name = Director)
  const nonDirectorEmployees = employees.filter(
    (emp) => emp.role_name !== "Director"
  );

  // Filter out Directors division (division_name = Directors)
  const nonDirectorDivisions = divisions.filter(
    (div) => div.division_name !== "Directors"
  );

  return (
    <div
      className="fixed inset-0 flex items-center justify-center z-50 p-4"
      style={{ backgroundColor: "rgba(0, 0, 0, 0.1)" }}
    >
      <div
        className="absolute inset-0"
        onClick={onClose}
        style={{ cursor: "pointer" }}
        title="Click to close"
      />
      <div
        className={`${modalBgClass} rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto relative z-60 border ${
          isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className={`p-6 border-b ${
            isLight ? "border-yellow-200" : "border-slate-600"
          }`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div
                className={`p-2 rounded-full ${
                  isLight ? "bg-yellow-100" : "bg-blue-900"
                }`}
              >
                <FaSave
                  className={`text-lg ${
                    isLight ? "text-amber-600" : "text-cyan-400"
                  }`}
                />
              </div>
              <div>
                <h2
                  className={`text-xl font-semibold ${
                    isLight ? "text-amber-800" : "text-slate-100"
                  }`}
                >
                  Edit Project
                </h2>
                <p
                  className={`text-sm ${
                    isLight ? "text-amber-700" : "text-slate-300"
                  } opacity-75`}
                >
                  Update project information
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              disabled={loading}
              className={`p-2 rounded-md transition-colors flex items-center justify-center w-8 h-8 ${
                isLight
                  ? "text-gray-400 hover:text-gray-600 hover:bg-gray-100"
                  : "text-gray-400 hover:text-gray-200 hover:bg-gray-700"
              } disabled:opacity-50`}
            >
              <FaTimes className="flex-shrink-0" />
            </button>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Project ID - Hidden field */}
          <input type="hidden" name="project_id" value={formData.project_id} />

          {/* Row 1: Project Name, Project Lead */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Project Name */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Project Name *
              </label>
              <input
                type="text"
                name="project_name"
                value={formData.project_name}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.project_name ? "border-red-500" : ""
                }`}
                placeholder="Enter project name"
                disabled={loading}
              />
              {errors.project_name && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.project_name}
                </p>
              )}
            </div>

            {/* Project Lead */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Project Lead *
              </label>
              <select
                name="project_lead_emp_id"
                value={formData.project_lead_emp_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.project_lead_emp_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {nonDirectorEmployees.map((employee) => (
                  <option
                    key={employee.employee_id}
                    value={employee.employee_id}
                  >
                    {employee.employee_name}
                  </option>
                ))}
              </select>
              {errors.project_lead_emp_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.project_lead_emp_id}
                </p>
              )}
            </div>
          </div>

          {/* Row 2: Project Type, Status */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Project Type */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Project Type *
              </label>
              <select
                name="type_id"
                value={formData.type_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.type_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {projectTypes.map((type) => (
                  <option key={type.type_id} value={type.type_id}>
                    {type.type_name}
                  </option>
                ))}
              </select>
              {errors.type_id && (
                <p className="text-red-500 text-sm mt-1">{errors.type_id}</p>
              )}
            </div>

            {/* Project Status */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Project Status *
              </label>
              <select
                name="status_id"
                value={formData.status_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.status_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {projectStatuses.map((status) => (
                  <option key={status.status_id} value={status.status_id}>
                    {status.status_name}
                  </option>
                ))}
              </select>
              {errors.status_id && (
                <p className="text-red-500 text-sm mt-1">{errors.status_id}</p>
              )}
            </div>
          </div>

          {/* Row 3: Invoice Status, Priority Level */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Invoice Status */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Invoice Status *
              </label>
              <select
                name="invoice_status_id"
                value={formData.invoice_status_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.invoice_status_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {invoiceStatuses.map((invoice) => (
                  <option
                    key={invoice.invoice_status_id}
                    value={invoice.invoice_status_id}
                  >
                    {invoice.invoice_status_name}
                  </option>
                ))}
              </select>
              {errors.invoice_status_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.invoice_status_id}
                </p>
              )}
            </div>

            {/* Priority Level */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Priority Level *
              </label>
              <select
                name="priority_level_id"
                value={formData.priority_level_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.priority_level_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {projectPriorities.map((priority) => (
                  <option
                    key={priority.priority_level_id}
                    value={priority.priority_level_id}
                  >
                    {priority.priority_level_name}
                  </option>
                ))}
              </select>
              {errors.priority_level_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.priority_level_id}
                </p>
              )}
            </div>
          </div>

          {/* Row 4: Division */}
          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            {/* Division */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Division *
              </label>
              <select
                name="division_id"
                value={formData.division_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.division_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                {nonDirectorDivisions.map((division) => (
                  <option
                    key={division.division_id}
                    value={division.division_id}
                  >
                    {division.division_name}
                  </option>
                ))}
              </select>
              {errors.division_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.division_id}
                </p>
              )}
            </div>

            {/* PO Status */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                PO Status *
              </label>
              <select
                name="po_status"
                value={formData.po_status}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.po_status ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                <option value="">Select PO Status</option>
                {poStatuses.map((poStatus) => (
                  <option
                    key={poStatus.id}
                    value={poStatus.state}
                  >
                    {poStatus.state}
                  </option>
                ))}
              </select>
              {errors.po_status && (
                <p className="text-red-500 text-sm mt-1">{errors.po_status}</p>
              )}
            </div>
          </div>

          {/* Row 5: Start Date, Deadline */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Start Date */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Start Date
              </label>
              <input
                type="date"
                name="project_start_date"
                value={formData.project_start_date}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass}`}
                disabled={loading}
              />
            </div>

            {/* Deadline */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Deadline
              </label>
              <input
                type="date"
                name="deadline"
                value={formData.deadline}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass}`}
                disabled={loading}
              />
            </div>
          </div>

          {/* Row 5: Progress, Estimated Hours, Actual Hours */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Progress */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Progress (%)
              </label>
              <input
                type="number"
                name="percent_completed"
                value={formData.percent_completed}
                onChange={handleInputChange}
                min="0"
                max="100"
                step="1"
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.percent_completed ? "border-red-500" : ""
                }`}
                placeholder="0-100"
                disabled={loading}
              />
              {errors.percent_completed && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.percent_completed}
                </p>
              )}
            </div>

            {/* Estimated Hours */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Estimated Hours
              </label>
              <input
                type="number"
                name="estimated_hours"
                value={formData.estimated_hours}
                onChange={handleInputChange}
                min="0"
                step="0.01"
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.estimated_hours ? "border-red-500" : ""
                }`}
                placeholder="0.00"
                disabled={loading}
              />
              {errors.estimated_hours && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.estimated_hours}
                </p>
              )}
            </div>

            {/* Actual Hours */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Actual Hours
              </label>
              <input
                type="number"
                name="actual_hours"
                value={formData.actual_hours}
                onChange={handleInputChange}
                min="0"
                step="0.01"
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.actual_hours ? "border-red-500" : ""
                }`}
                placeholder="0.00"
                disabled={loading}
              />
              {errors.actual_hours && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.actual_hours}
                </p>
              )}
            </div>
          </div>

          {/* Row 6: Remarks */}
          <div>
            <label className={`block text-sm font-medium ${textClass} mb-2`}>
              Remarks
            </label>
            <textarea
              name="remarks"
              value={formData.remarks}
              onChange={handleInputChange}
              rows={3}
              className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} resize-none`}
              placeholder="Enter any additional notes..."
              disabled={loading}
            />
          </div>

          {/* Buttons */}
          <div
            className={`flex gap-3 pt-4 mt-4 border-t ${
              isLight ? "border-yellow-200" : "border-slate-600"
            }`}
          >
            <button
              type="button"
              onClick={onClose}
              disabled={loading}
              className={`flex-1 px-4 py-2 rounded-md font-medium text-sm transition-colors border ${
                isLight
                  ? "border-yellow-300 text-amber-700 hover:bg-yellow-50 bg-white"
                  : "border-slate-600 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-500"
              } disabled:opacity-50 disabled:cursor-not-allowed`}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className={`flex-1 px-4 py-2 rounded-md font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 ${buttonClass}`}
            >
              {loading ? (
                <>
                  <FaSpinner className="animate-spin text-sm" />
                  <span>Saving...</span>
                </>
              ) : (
                <>
                  <FaSave className="text-sm" />
                  <span>Save Changes</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default EditProjectModal;
