/**
 * EditJobModal Component
 * Edit existing job posting with all bilingual fields
 */

"use client";

import { useState, useEffect } from "react";
import { X, Save } from "lucide-react";

interface Job {
  id: string;
  slug: string;
  title_translations: { ar: string; en: string };
  department: string;
  department_label: { ar: string; en: string };
  location_translations: { ar: string; en: string };
  contract_type: string;
  contract_type_label: { ar: string; en: string };
  level: string;
  level_label: { ar: string; en: string };
  compensation_translations: { ar: string; en: string };
  status: string;
  opening_at: string;
  closing_at: string | null;
  responsibilities: { ar: string[]; en: string[] };
  requirements: { ar: string[]; en: string[] };
  skills: { ar: string[]; en: string[] };
  benefits: { ar: string[]; en: string[] };
  nice_to_have: { ar: string[]; en: string[] };
  workday_expectations: { ar: string[]; en: string[] };
  application_instructions: { ar: string; en: string };
}

interface EditJobModalProps {
  isOpen: boolean;
  job: Job | any;
  onClose: () => void;
  onJobUpdated: () => void;
}

export default function EditJobModal({
  isOpen,
  job,
  onClose,
  onJobUpdated,
}: EditJobModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState<any>({});

  useEffect(() => {
    if (job) {
      setFormData({
        slug: job.slug || "",
        titleEn: job.title_translations?.en || "",
        titleAr: job.title_translations?.ar || "",
        department: job.department || "engineering",
        departmentLabelEn: job.department_label?.en || "",
        departmentLabelAr: job.department_label?.ar || "",
        locationEn: job.location_translations?.en || "",
        locationAr: job.location_translations?.ar || "",
        contractType: job.contract_type || "full-time",
        level: job.level || "mid",
        salaryEn: job.compensation_translations?.en || "",
        salaryAr: job.compensation_translations?.ar || "",
        status: job.status || "draft",
        openingAt: job.opening_at ? job.opening_at.split("T")[0] : "",
        closingAt: job.closing_at ? job.closing_at.split("T")[0] : "",
        responsibilitiesEn: Array.isArray(job.responsibilities?.en)
          ? job.responsibilities.en.join("\n")
          : "",
        responsibilitiesAr: Array.isArray(job.responsibilities?.ar)
          ? job.responsibilities.ar.join("\n")
          : "",
        requirementsEn: Array.isArray(job.requirements?.en)
          ? job.requirements.en.join("\n")
          : "",
        requirementsAr: Array.isArray(job.requirements?.ar)
          ? job.requirements.ar.join("\n")
          : "",
        skillsEn: Array.isArray(job.skills?.en) ? job.skills.en.join("\n") : "",
        skillsAr: Array.isArray(job.skills?.ar) ? job.skills.ar.join("\n") : "",
        benefitsEn: Array.isArray(job.benefits?.en)
          ? job.benefits.en.join("\n")
          : "",
        benefitsAr: Array.isArray(job.benefits?.ar)
          ? job.benefits.ar.join("\n")
          : "",
        niceToHaveEn: Array.isArray(job.nice_to_have?.en)
          ? job.nice_to_have.en.join("\n")
          : "",
        niceToHaveAr: Array.isArray(job.nice_to_have?.ar)
          ? job.nice_to_have.ar.join("\n")
          : "",
      });
    }
  }, [job]);

  if (!isOpen) return null;

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev: any) => ({ ...prev, [field]: value }));
  };

  const splitByNewline = (text: string): string[] => {
    return text
      .split("\n")
      .map((line) => line.trim())
      .filter((line) => line.length > 0);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const updateData = {
        slug: formData.slug,
        title_translations: {
          en: formData.titleEn,
          ar: formData.titleAr,
        },
        department: formData.department,
        department_label: {
          en: formData.departmentLabelEn,
          ar: formData.departmentLabelAr,
        },
        location_translations: {
          en: formData.locationEn,
          ar: formData.locationAr,
        },
        contract_type: formData.contractType,
        level: formData.level,
        compensation_translations: {
          en: formData.salaryEn,
          ar: formData.salaryAr,
        },
        responsibilities: {
          en: splitByNewline(formData.responsibilitiesEn),
          ar: splitByNewline(formData.responsibilitiesAr),
        },
        requirements: {
          en: splitByNewline(formData.requirementsEn),
          ar: splitByNewline(formData.requirementsAr),
        },
        skills: {
          en: splitByNewline(formData.skillsEn),
          ar: splitByNewline(formData.skillsAr),
        },
        benefits: {
          en: splitByNewline(formData.benefitsEn),
          ar: splitByNewline(formData.benefitsAr),
        },
        nice_to_have: {
          en: splitByNewline(formData.niceToHaveEn),
          ar: splitByNewline(formData.niceToHaveAr),
        },
        status: formData.status,
        opening_at: formData.openingAt
          ? new Date(formData.openingAt).toISOString()
          : undefined,
        closing_at: formData.closingAt
          ? new Date(formData.closingAt).toISOString()
          : null,
      };

      const response = await fetch(`/api/staff/jobs/${job.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updateData),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to update job");
      }

      alert("Job updated successfully!");
      onJobUpdated();
    } catch (error: any) {
      console.error("Error updating job:", error);
      alert(error.message || "Failed to update job");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between z-10">
          <h2 className="text-2xl font-bold text-brand-ink">
            Edit Job: {formData.titleEn}
          </h2>
          <button
            type="button"
            aria-label="Close"
            onClick={onClose}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-all"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Title */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Title (EN)
              </label>
              <input
                type="text"
                value={formData.titleEn}
                onChange={(e) => handleInputChange("titleEn", e.target.value)}
                className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                العنوان (AR)
              </label>
              <input
                type="text"
                value={formData.titleAr}
                onChange={(e) => handleInputChange("titleAr", e.target.value)}
                className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green"
                dir="rtl"
                required
              />
            </div>
          </div>

          {/* Status */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Status
            </label>
            <select
              value={formData.status}
              onChange={(e) => handleInputChange("status", e.target.value)}
              className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green"
            >
              <option value="draft">Draft</option>
              <option value="open">Open</option>
              <option value="paused">Paused</option>
              <option value="closed">Closed</option>
            </select>
          </div>

          {/* Responsibilities */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Responsibilities (EN)
              </label>
              <textarea
                value={formData.responsibilitiesEn}
                onChange={(e) =>
                  handleInputChange("responsibilitiesEn", e.target.value)
                }
                rows={6}
                className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green font-mono text-sm"
                placeholder="One per line"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                المسؤوليات (AR)
              </label>
              <textarea
                value={formData.responsibilitiesAr}
                onChange={(e) =>
                  handleInputChange("responsibilitiesAr", e.target.value)
                }
                rows={6}
                className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green font-mono text-sm"
                dir="rtl"
                placeholder="واحد في كل سطر"
              />
            </div>
          </div>

          {/* Form Actions */}
          <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              className="px-6 py-3 border-2 border-gray-300 text-gray-700 font-semibold rounded-lg hover:bg-gray-50"
              disabled={isSubmitting}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 disabled:opacity-50 flex items-center gap-2"
            >
              <Save className="w-5 h-5" />
              {isSubmitting ? "Saving..." : "Save Changes"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
