// components/staff/contracts/SalaireParDateEditor.tsx
"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Edit2, Save, X, CalendarPlus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import DatesQuantityModal from "@/components/DatesQuantityModal";

interface SalaireItem {
  numero: number;
  montant: number;
}

interface SalaireParJour {
  date: string;
  items?: SalaireItem[];
  montant?: number;
}

interface SalairesParDate {
  representations?: SalaireParJour[];
  repetitions?: SalaireParJour[];
  jours_travail?: SalaireParJour[];
  total_calcule: number;
}

interface SalaireParDateEditorProps {
  salairesParDate: SalairesParDate;
  contractId: string;
  onUpdate?: (newSalaires: SalairesParDate) => void;
  categoriePro?: "Artiste" | "Technicien";
}

export function SalaireParDateEditor({ salairesParDate, contractId, onUpdate, categoriePro }: SalaireParDateEditorProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editedData, setEditedData] = useState<SalairesParDate>(salairesParDate);
  const [isSaving, setIsSaving] = useState(false);
  const [isDatesModalOpen, setIsDatesModalOpen] = useState(false);
  const [pendingDates, setPendingDates] = useState<string[]>([]);

  // Calculer le total
  const calculateTotal = (data: SalairesParDate): number => {
    let total = 0;

    // Représentations
    data.representations?.forEach(rep => {
      rep.items?.forEach(item => {
        total += item.montant;
      });
    });

    // Répétitions
    data.repetitions?.forEach(rep => {
      rep.items?.forEach(item => {
        total += item.montant;
      });
    });

    // Jours travaillés
    data.jours_travail?.forEach(jour => {
      if (jour.montant) {
        total += jour.montant;
      }
    });

    return total;
  };

  // Mettre à jour le montant d'un item de représentation
  const updateRepresentationItem = (repIdx: number, itemIdx: number, newMontant: string) => {
    const newData = { ...editedData };
    if (newData.representations && newData.representations[repIdx]?.items) {
      newData.representations[repIdx].items[itemIdx].montant = parseFloat(newMontant) || 0;
      newData.total_calcule = calculateTotal(newData);
      setEditedData(newData);
    }
  };

  // Mettre à jour le montant d'un item de répétition
  const updateRepetitionItem = (repIdx: number, itemIdx: number, newMontant: string) => {
    const newData = { ...editedData };
    if (newData.repetitions && newData.repetitions[repIdx]?.items) {
      newData.repetitions[repIdx].items[itemIdx].montant = parseFloat(newMontant) || 0;
      newData.total_calcule = calculateTotal(newData);
      setEditedData(newData);
    }
  };

  // Mettre à jour le montant d'un jour travaillé
  const updateJourTravail = (jourIdx: number, newMontant: string) => {
    const newData = { ...editedData };
    if (newData.jours_travail && newData.jours_travail[jourIdx]) {
      newData.jours_travail[jourIdx].montant = parseFloat(newMontant) || 0;
      newData.total_calcule = calculateTotal(newData);
      setEditedData(newData);
    }
  };

  // Supprimer un jour travaillé
  const deleteJourTravail = (jourIdx: number) => {
    const newData = { ...editedData };
    if (newData.jours_travail) {
      newData.jours_travail = newData.jours_travail.filter((_, idx) => idx !== jourIdx);
      newData.total_calcule = calculateTotal(newData);
      setEditedData(newData);
    }
  };

  // Ouvrir le modal de sélection de dates
  const handleOpenDatesModal = () => {
    const existingDates = editedData.jours_travail?.map(jour => jour.date) || [];
    setPendingDates(existingDates);
    setIsDatesModalOpen(true);
  };

  // Appliquer les nouvelles dates sélectionnées
  const handleApplyDates = (result: {
    selectedDates: string[];
    hasMultiMonth: boolean;
    pdfFormatted: string;
    globalQuantity?: number;
    globalDuration?: "3" | "4";
    totalHours?: number;
    totalQuantities?: number;
  }) => {
    const newData = { ...editedData };
    
    // Créer les nouveaux jours de travail avec les montants existants ou 0
    newData.jours_travail = result.selectedDates.map((date) => {
      const existing = editedData.jours_travail?.find(j => j.date === date);
      return {
        date: date,
        montant: existing?.montant || 0,
      };
    });
    
    newData.total_calcule = calculateTotal(newData);
    setEditedData(newData);
    setIsDatesModalOpen(false);
  };

  // Sauvegarder les modifications
  const handleSave = async () => {
    setIsSaving(true);
    try {
      const response = await fetch(`/api/staff/contrats/${contractId}/salaires-par-date`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ salaires_par_date: editedData }),
      });

      if (!response.ok) {
        throw new Error("Erreur lors de la mise à jour");
      }

      toast.success("Salaires par date mis à jour");
      setIsEditing(false);
      
      if (onUpdate) {
        onUpdate(editedData);
      }
    } catch (error) {
      console.error("Error saving salaires par date:", error);
      toast.error("Impossible de sauvegarder les modifications");
    } finally {
      setIsSaving(false);
    }
  };

  // Annuler les modifications
  const handleCancel = () => {
    setEditedData(salairesParDate);
    setIsEditing(false);
  };

  const currentData = isEditing ? editedData : salairesParDate;

  return (
    <div className="mt-3 p-4 bg-slate-50 rounded-lg border border-slate-200">
      <div className="flex items-center justify-between mb-3">
        <div className="text-xs font-semibold text-slate-700">Détail des salaires par date</div>
        {!isEditing ? (
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => setIsEditing(true)}
            className="h-7 px-2 text-xs"
          >
            <Edit2 className="h-3 w-3 mr-1" />
            Modifier
          </Button>
        ) : (
          <div className="flex gap-2">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleCancel}
              disabled={isSaving}
              className="h-7 px-2 text-xs"
            >
              <X className="h-3 w-3 mr-1" />
              Annuler
            </Button>
            <Button
              type="button"
              variant="default"
              size="sm"
              onClick={handleSave}
              disabled={isSaving}
              className="h-7 px-2 text-xs"
            >
              <Save className="h-3 w-3 mr-1" />
              {isSaving ? "Sauvegarde..." : "Enregistrer"}
            </Button>
          </div>
        )}
      </div>

      <div className="space-y-4">
        {/* Représentations */}
        {currentData.representations && currentData.representations.length > 0 && (
          <div>
            <div className="text-xs font-semibold text-indigo-700 uppercase tracking-wide mb-2">Représentations</div>
            <div className="overflow-hidden rounded-md border border-slate-200">
              <table className="w-full text-xs">
                <thead className="bg-slate-100">
                  <tr>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Date</th>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Type</th>
                    <th className="text-right px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Montant</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-slate-100">
                  {currentData.representations.map((rep, repIdx) => {
                    if (!rep.items || rep.items.length === 0) return null;
                    
                    // Regrouper tous les items de cette date en une seule ligne
                    const typesLabel = rep.items.map(item => `R${item.numero}`).join(', ');
                    const totalMontant = rep.items.reduce((sum, item) => sum + item.montant, 0);
                    
                    return (
                      <tr key={repIdx} className="hover:bg-slate-50">
                        <td className="px-3 py-2 font-medium text-slate-700">{rep.date}</td>
                        <td className="px-3 py-2 text-slate-600">{typesLabel}</td>
                        <td className="px-3 py-2 text-right">
                          {isEditing ? (
                            <div className="space-y-1">
                              {rep.items.map((item, itemIdx) => (
                                <div key={itemIdx} className="flex items-center justify-end gap-2">
                                  <span className="text-xs text-slate-500">R{item.numero}:</span>
                                  <Input
                                    type="number"
                                    step="0.01"
                                    value={item.montant}
                                    onChange={(e) => updateRepresentationItem(repIdx, itemIdx, e.target.value)}
                                    className="h-6 text-right text-xs w-20"
                                  />
                                </div>
                              ))}
                            </div>
                          ) : (
                            <span className="font-semibold text-slate-900">{totalMontant.toFixed(2)} €</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Répétitions */}
        {currentData.repetitions && currentData.repetitions.length > 0 && (
          <div>
            <div className="text-xs font-semibold text-purple-700 uppercase tracking-wide mb-2">Répétitions</div>
            <div className="overflow-hidden rounded-md border border-slate-200">
              <table className="w-full text-xs">
                <thead className="bg-slate-100">
                  <tr>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Date</th>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Type</th>
                    <th className="text-right px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Montant</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-slate-100">
                  {currentData.repetitions.map((rep, repIdx) => {
                    if (!rep.items || rep.items.length === 0) return null;
                    
                    // Regrouper tous les items de cette date en une seule ligne
                    const typesLabel = rep.items.map(item => `S${item.numero}`).join(', ');
                    const totalMontant = rep.items.reduce((sum, item) => sum + item.montant, 0);
                    
                    return (
                      <tr key={repIdx} className="hover:bg-slate-50">
                        <td className="px-3 py-2 font-medium text-slate-700">{rep.date}</td>
                        <td className="px-3 py-2 text-slate-600">{typesLabel}</td>
                        <td className="px-3 py-2 text-right">
                          {isEditing ? (
                            <div className="space-y-1">
                              {rep.items.map((item, itemIdx) => (
                                <div key={itemIdx} className="flex items-center justify-end gap-2">
                                  <span className="text-xs text-slate-500">S{item.numero}:</span>
                                  <Input
                                    type="number"
                                    step="0.01"
                                    value={item.montant}
                                    onChange={(e) => updateRepetitionItem(repIdx, itemIdx, e.target.value)}
                                    className="h-6 text-right text-xs w-20"
                                  />
                                </div>
                              ))}
                            </div>
                          ) : (
                            <span className="font-semibold text-slate-900">{totalMontant.toFixed(2)} €</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Jours travaillés */}
        {currentData.jours_travail && currentData.jours_travail.length > 0 && (
          <div>
            <div className="flex items-center justify-between mb-2">
              <div className="text-xs font-semibold text-green-700 uppercase tracking-wide">Jours travaillés</div>
              {isEditing && categoriePro === "Technicien" && (
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={handleOpenDatesModal}
                  className="h-6 px-2 text-xs"
                >
                  <CalendarPlus className="h-3 w-3 mr-1" />
                  Modifier les dates
                </Button>
              )}
            </div>
            <div className="overflow-hidden rounded-md border border-slate-200">
              <table className="w-full text-xs">
                <thead className="bg-slate-100">
                  <tr>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Date</th>
                    <th className="text-left px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Type</th>
                    <th className="text-right px-3 py-2 font-semibold text-slate-700 border-b border-slate-200">Montant</th>
                    {isEditing && categoriePro === "Technicien" && (
                      <th className="text-center px-3 py-2 font-semibold text-slate-700 border-b border-slate-200 w-16">Actions</th>
                    )}
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-slate-100">
                  {currentData.jours_travail.map((jour, jourIdx) => (
                    <tr key={jourIdx} className="hover:bg-slate-50">
                      <td className="px-3 py-2 font-medium text-slate-700">{jour.date}</td>
                      <td className="px-3 py-2 text-slate-600">Jour</td>
                      <td className="px-3 py-2 text-right">
                        {isEditing ? (
                          <Input
                            type="number"
                            step="0.01"
                            value={jour.montant || 0}
                            onChange={(e) => updateJourTravail(jourIdx, e.target.value)}
                            className="h-7 text-right text-xs w-24 ml-auto"
                          />
                        ) : (
                          <span className="font-semibold text-slate-900">{(jour.montant || 0).toFixed(2)} €</span>
                        )}
                      </td>
                      {isEditing && categoriePro === "Technicien" && (
                        <td className="px-3 py-2 text-center">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => deleteJourTravail(jourIdx)}
                            className="h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Total */}
        <div className="pt-3 border-t border-slate-200">
          <div className="flex justify-between items-center">
            <span className="text-xs font-semibold text-slate-700">Total</span>
            <span className="text-sm font-bold text-indigo-900">{currentData.total_calcule.toFixed(2)} €</span>
          </div>
        </div>
      </div>

      {/* Modal de sélection de dates pour les techniciens */}
      {categoriePro === "Technicien" && (
        <DatesQuantityModal
          isOpen={isDatesModalOpen}
          onClose={() => setIsDatesModalOpen(false)}
          selectedDates={pendingDates}
          dateType="jours_travail"
          onApply={handleApplyDates}
          allowSkipHoursByDay={true}
        />
      )}
    </div>
  );
}
