"use client";

import { useState, useEffect, useMemo } from "react";
import { Search, ChevronDown } from "lucide-react";
import { OriginalContractData } from "@/types/amendments";

interface AmendmentObjetFormProps {
  originalData: OriginalContractData;
  data: any;
  onChange: (data: any) => void;
}

export default function AmendmentObjetForm({
  originalData,
  data,
  onChange,
}: AmendmentObjetFormProps) {
  const [professionsArtiste, setProfessionsArtiste] = useState<any[]>([]);
  const [professionsTechnicien, setProfessionsTechnicien] = useState<any[]>([]);
  const [productions, setProductions] = useState<any[]>([]);
  
  const [professionSearch, setProfessionSearch] = useState("");
  const [productionSearch, setProductionSearch] = useState("");
  const [showProfessionList, setShowProfessionList] = useState(false);
  const [showProductionList, setShowProductionList] = useState(false);

  // Déterminer le type de contrat (Artiste ou Technicien)
  const isArtist = originalData.type_de_contrat === "CDD d'usage";

  // Charger les professions
  useEffect(() => {
    async function loadProfessions() {
      try {
        // Charger professions artistes (professions-feminisations.json)
        const resArtiste = await fetch("/data/professions-feminisations.json");
        if (resArtiste.ok) {
          const dataArtiste = await resArtiste.json();
          setProfessionsArtiste(dataArtiste);
        }

        // Charger professions techniciens
        const resTech = await fetch("/data/professions-techniciens.json");
        if (resTech.ok) {
          const dataTech = await resTech.json();
          setProductions(dataTech);
        }
      } catch (error) {
        console.error("Erreur chargement professions:", error);
      }
    }
    loadProfessions();
  }, []);

  // Charger les productions de l'organisation
  useEffect(() => {
    async function loadProductions() {
      if (!originalData.org_id) return;
      try {
        const response = await fetch(`/api/productions?org_id=${originalData.org_id}`);
        if (response.ok) {
          const prods = await response.json();
          setProductions(prods);
        }
      } catch (error) {
        console.error("Erreur chargement productions:", error);
      }
    }
    loadProductions();
  }, [originalData.org_id]);

  // Filtrer les professions selon la recherche
  const filteredProfessions = useMemo(() => {
    const list = isArtist ? professionsArtiste : professionsTechnicien;
    if (!professionSearch) return list;
    
    const term = professionSearch.toLowerCase();
    return list.filter((p: any) => {
      const code = isArtist ? p.profession_code : p.code;
      const label = isArtist ? p.profession_label : p.label;
      return (
        code?.toLowerCase().includes(term) ||
        label?.toLowerCase().includes(term)
      );
    });
  }, [isArtist, professionsArtiste, professionsTechnicien, professionSearch]);

  // Filtrer les productions selon la recherche
  const filteredProductions = useMemo(() => {
    if (!productionSearch) return productions;
    const term = productionSearch.toLowerCase();
    return productions.filter((p: any) =>
      p.nom?.toLowerCase().includes(term) ||
      p.numero_objet?.toLowerCase().includes(term)
    );
  }, [productions, productionSearch]);

  const handleProfessionSelect = (profession: any) => {
    const code = isArtist ? profession.profession_code : profession.code;
    const label = isArtist ? profession.profession_label : profession.label;
    
    onChange({
      ...data,
      profession_code: code,
      profession_label: label,
    });
    setProfessionSearch(`${code} - ${label}`);
    setShowProfessionList(false);
  };

  const handleProductionSelect = (production: any) => {
    onChange({
      ...data,
      production_name: production.nom,
      production_numero_objet: production.numero_objet || "",
    });
    setProductionSearch(production.nom);
    setShowProductionList(false);
  };

  // Initialiser les champs de recherche avec les valeurs actuelles
  useEffect(() => {
    if (data.profession_code && data.profession_label) {
      setProfessionSearch(`${data.profession_code} - ${data.profession_label}`);
    }
    if (data.production_name) {
      setProductionSearch(data.production_name);
    }
  }, []);

  return (
    <div className="bg-indigo-50/50 rounded-lg p-4 border border-indigo-200 space-y-4">
      <h3 className="font-medium text-slate-900 text-sm">Modification de l'objet</h3>

      {/* Profession */}
      <div>
        <label className="block text-xs font-medium text-slate-700 mb-2">
          Profession
        </label>
        <div className="text-xs text-slate-500 mb-2">
          Actuellement : {originalData.profession || "-"}
        </div>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
          <input
            type="text"
            placeholder="Rechercher une profession..."
            value={professionSearch}
            onChange={(e) => {
              setProfessionSearch(e.target.value);
              setShowProfessionList(true);
            }}
            onFocus={() => setShowProfessionList(true)}
            className="w-full pl-10 pr-4 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          {showProfessionList && filteredProfessions.length > 0 && (
            <div className="absolute z-10 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-60 overflow-y-auto">
              {filteredProfessions.map((profession: any, idx: number) => {
                const code = isArtist ? profession.profession_code : profession.code;
                const label = isArtist ? profession.profession_label : profession.label;
                return (
                  <button
                    key={idx}
                    onClick={() => handleProfessionSelect(profession)}
                    className="w-full px-3 py-2 text-left hover:bg-slate-50 text-sm"
                  >
                    <span className="font-medium text-slate-900">{code}</span>
                    <span className="text-slate-600"> - {label}</span>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Production */}
      <div>
        <label className="block text-xs font-medium text-slate-700 mb-2">
          Production
        </label>
        <div className="text-xs text-slate-500 mb-2">
          Actuellement : {originalData.production_name || "-"}
          {originalData.numero_objet && ` (${originalData.numero_objet})`}
        </div>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
          <input
            type="text"
            placeholder="Rechercher une production..."
            value={productionSearch}
            onChange={(e) => {
              setProductionSearch(e.target.value);
              setShowProductionList(true);
            }}
            onFocus={() => setShowProductionList(true)}
            className="w-full pl-10 pr-4 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          {showProductionList && filteredProductions.length > 0 && (
            <div className="absolute z-10 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-60 overflow-y-auto">
              {filteredProductions.map((production: any) => (
                <button
                  key={production.id}
                  onClick={() => handleProductionSelect(production)}
                  className="w-full px-3 py-2 text-left hover:bg-slate-50 text-sm"
                >
                  <div className="font-medium text-slate-900">{production.nom}</div>
                  {production.numero_objet && (
                    <div className="text-xs text-slate-500">{production.numero_objet}</div>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
