"use client";

import { useState, useEffect, useRef, DragEvent } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X, Save, Plus, Upload, FileText } from "lucide-react";
import { toast } from "sonner";

interface PayslipModalProps {
  isOpen: boolean;
  payslip?: any;
  contractId: string;
  contractNumber?: string;
  onClose: () => void;
  onSuccess: () => void;
}

export function PayslipModal({ 
  isOpen, 
  payslip, 
  contractId, 
  contractNumber,
  onClose, 
  onSuccess 
}: PayslipModalProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [isGeneratingUrl, setIsGeneratingUrl] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [formData, setFormData] = useState({
    pay_number: "",
    pay_date: "",
    period_start: "",
    period_end: "",
    gross_amount: "",
    net_amount: "",
    net_after_withholding: "",
    employer_cost: "",
    processed: false,
    aem_status: "À traiter",
    transfer_done: false,
    storage_path: "",
    storage_url: ""
  });

  // Bloquer le scroll de la page quand la modal est ouverte
  useEffect(() => {
    if (isOpen) {
      // Sauvegarder la position actuelle du scroll
      const scrollY = window.scrollY;
      
      // Appliquer les styles pour bloquer le scroll
      document.body.style.position = 'fixed';
      document.body.style.top = `-${scrollY}px`;
      document.body.style.width = '100%';
      
      return () => {
        // Restaurer le scroll quand la modal se ferme
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.width = '';
        window.scrollTo(0, scrollY);
      };
    }
  }, [isOpen]);

  useEffect(() => {
    if (isOpen) {
      if (payslip) {
        // Mode édition - pré-remplir avec les données existantes
        setFormData({
          pay_number: payslip.pay_number?.toString() || "",
          pay_date: payslip.pay_date ? String(payslip.pay_date).slice(0, 10) : "",
          period_start: payslip.period_start ? String(payslip.period_start).slice(0, 10) : "",
          period_end: payslip.period_end ? String(payslip.period_end).slice(0, 10) : "",
          gross_amount: payslip.gross_amount?.toString() || "",
          net_amount: payslip.net_amount?.toString() || "",
          net_after_withholding: payslip.net_after_withholding?.toString() || "",
          employer_cost: payslip.employer_cost?.toString() || "",
          processed: payslip.processed || false,
          aem_status: payslip.aem_status || "À traiter",
          transfer_done: payslip.transfer_done || false,
          storage_path: payslip.storage_path || "",
          storage_url: payslip.storage_url || ""
        });
      } else {
        // Mode création - formulaire vide
        setFormData({
          pay_number: "",
          pay_date: "",
          period_start: "",
          period_end: "",
          gross_amount: "",
          net_amount: "",
          net_after_withholding: "",
          employer_cost: "",
          processed: false,
          aem_status: "À traiter",
          transfer_done: false,
          storage_path: "",
          storage_url: ""
        });
      }
      setUploadedFile(null);
    }
  }, [isOpen, payslip]);

  const handleFileUpload = async (file: File) => {
    if (!file || !file.type.includes('pdf')) {
      toast.error("Veuillez sélectionner un fichier PDF");
      return;
    }

    setIsUploading(true);
    
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('prefix', 'paies/');
      
      const response = await fetch('/api/upload-s3', {
        method: 'POST',
        body: formData
      });
      
      if (!response.ok) {
        throw new Error('Erreur lors du téléchargement');
      }
      
      const result = await response.json();
      
      setFormData(prev => ({
        ...prev,
        storage_path: result.key,
        storage_url: result.url
      }));
      
      setUploadedFile(file);
      toast.success("Fichier téléchargé avec succès");
    } catch (error) {
      console.error("Erreur upload:", error);
      toast.error("Erreur lors du téléchargement du fichier");
    } finally {
      setIsUploading(false);
    }
  };

  // Gestion du drag & drop
  const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = async (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length === 0) return;

    const file = files[0];
    
    // Vérifier que c'est un PDF
    if (file.type !== 'application/pdf') {
      toast.error("Seuls les fichiers PDF sont acceptés");
      return;
    }

    await handleFileUpload(file);
  };

  const handleViewFile = async () => {
    if (!formData.storage_path) {
      toast.error("Aucun fichier disponible");
      return;
    }

    setIsGeneratingUrl(true);

    try {
      const response = await fetch('/api/s3-presigned', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          key: formData.storage_path
        })
      });

      if (!response.ok) {
        throw new Error('Erreur lors de la génération de l\'URL');
      }

      const result = await response.json();
      
      // Ouvrir le fichier dans un nouvel onglet
      window.open(result.url, '_blank');
      toast.success("Fichier ouvert dans un nouvel onglet");
    } catch (error) {
      console.error("Erreur génération URL:", error);
      toast.error("Erreur lors de l'accès au fichier");
    } finally {
      setIsGeneratingUrl(false);
    }
  };

  const handleSubmit = async () => {
    setIsLoading(true);
    
    try {
      console.log("contractId dans modal:", contractId, typeof contractId);
      
      const payload = {
        pay_number: formData.pay_number ? parseInt(formData.pay_number) : null,
        pay_date: formData.pay_date || null,
        period_start: formData.period_start || null,
        period_end: formData.period_end || null,
        gross_amount: formData.gross_amount ? parseFloat(formData.gross_amount) : null,
        net_amount: formData.net_amount ? parseFloat(formData.net_amount) : null,
        net_after_withholding: formData.net_after_withholding ? parseFloat(formData.net_after_withholding) : null,
        employer_cost: formData.employer_cost ? parseFloat(formData.employer_cost) : null,
        processed: formData.processed,
        aem_status: formData.aem_status,
        transfer_done: formData.transfer_done,
        storage_path: formData.storage_path || null,
        storage_url: formData.storage_url || null,
        contract_id: contractId,
        organization_id: payslip?.organization_id || null
      };

      console.log("Payload envoyé:", payload);

      let response;
      if (payslip) {
        // Mise à jour
        response = await fetch(`/api/staff/payslips/${payslip.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
      } else {
        // Création
        response = await fetch(`/api/staff/payslips`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
      }

      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.error || "Erreur lors de la sauvegarde");
      }

      toast.success(payslip ? "Paie mise à jour avec succès" : "Paie créée avec succès");
      onSuccess();
      onClose();
    } catch (error) {
      console.error("Erreur:", error);
      toast.error(error instanceof Error ? error.message : "Erreur lors de la sauvegarde");
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange = (field: string, value: string | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const getProcessedStatusText = () => {
    if (!formData.processed) return "À traiter";
    return formData.transfer_done ? "Traitée" : "En cours de traitement";
  };

  const getProcessedStatusColor = () => {
    if (!formData.processed) return "text-red-600 bg-red-50";
    return formData.transfer_done ? "text-green-600 bg-green-50" : "text-orange-600 bg-orange-50";
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-3xl max-w-2xl w-full shadow-2xl max-h-[90vh] flex flex-col">
        <div className="flex items-center justify-between p-8 pb-6 border-b">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">
              {payslip ? "Modifier la paie" : "Ajouter une paie"}
            </h2>
            <div className="flex items-center gap-4 mt-2">
              {payslip && formData.pay_number && (
                <span className="text-sm text-gray-600">
                  Paie #{formData.pay_number}
                </span>
              )}
              {contractNumber && (
                <span className="text-sm text-gray-600">
                  Contrat {contractNumber}
                </span>
              )}
            </div>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            className="rounded-full h-8 w-8"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        <div className="flex-1 overflow-y-auto p-8 pt-6">
          <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Numéro de paie
              </label>
              <Input
                type="number"
                value={formData.pay_number}
                onChange={(e) => handleChange("pay_number", e.target.value)}
                placeholder="1"
              />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Date de paie
              </label>
              <Input
                type="date"
                value={formData.pay_date}
                onChange={(e) => handleChange("pay_date", e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Début de période
              </label>
              <Input
                type="date"
                value={formData.period_start}
                onChange={(e) => handleChange("period_start", e.target.value)}
              />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Fin de période
              </label>
              <Input
                type="date"
                value={formData.period_end}
                onChange={(e) => handleChange("period_end", e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Montant brut
              </label>
              <Input
                type="number"
                step="0.01"
                value={formData.gross_amount}
                onChange={(e) => handleChange("gross_amount", e.target.value)}
                placeholder="0.00"
              />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Net avant PAS
              </label>
              <Input
                type="number"
                step="0.01"
                value={formData.net_amount}
                onChange={(e) => handleChange("net_amount", e.target.value)}
                placeholder="0.00"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Net à payer
              </label>
              <Input
                type="number"
                step="0.01"
                value={formData.net_after_withholding}
                onChange={(e) => handleChange("net_after_withholding", e.target.value)}
                placeholder="0.00"
              />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Coût total employeur
              </label>
              <Input
                type="number"
                step="0.01"
                value={formData.employer_cost}
                onChange={(e) => handleChange("employer_cost", e.target.value)}
                placeholder="0.00"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                État de traitement
              </label>
              <div className="space-y-2">
                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={formData.processed}
                    onChange={(e) => handleChange("processed", e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  <span className="text-sm text-gray-600">Traité</span>
                </label>
                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={formData.transfer_done}
                    onChange={(e) => handleChange("transfer_done", e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  <span className="text-sm text-gray-600">Virement effectué</span>
                </label>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">
                Statut AEM
              </label>
              <select
                value={formData.aem_status}
                onChange={(e) => handleChange("aem_status", e.target.value)}
                className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="À traiter">À traiter</option>
                <option value="OK">OK</option>
              </select>
            </div>
          </div>

          {/* Upload de fichier PDF */}
          <div>
            <label className="text-sm font-medium text-gray-700 mb-2 block">
              Bulletin de paie (PDF)
            </label>
            <div 
              className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
                isDragging 
                  ? 'border-blue-500 bg-blue-50' 
                  : 'border-gray-300 hover:border-gray-400'
              }`}
              onDragEnter={handleDragEnter}
              onDragLeave={handleDragLeave}
              onDragOver={handleDragOver}
              onDrop={handleDrop}
            >
              {formData.storage_url || uploadedFile ? (
                <div className="space-y-3">
                  <FileText className="mx-auto h-12 w-12 text-green-500" />
                  <div>
                    <p className="text-sm text-green-600 font-medium">
                      {uploadedFile ? uploadedFile.name : "Fichier existant"}
                    </p>
                    {formData.storage_path && (
                      <button
                        onClick={handleViewFile}
                        disabled={isGeneratingUrl}
                        className="text-xs text-blue-500 hover:underline disabled:text-gray-400 disabled:cursor-not-allowed"
                      >
                        {isGeneratingUrl ? "Génération..." : "Voir le fichier"}
                      </button>
                    )}
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isUploading}
                  >
                    {isUploading ? "Téléchargement..." : "Remplacer"}
                  </Button>
                </div>
              ) : (
                <div className="space-y-2">
                  <Upload className="mx-auto h-12 w-12 text-gray-400" />
                  <div>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={isUploading}
                    >
                      {isUploading ? (
                        <>
                          <div className="animate-spin rounded-full h-4 w-4 border-2 border-transparent border-t-gray-600 mr-2" />
                          Téléchargement...
                        </>
                      ) : (
                        <>
                          <Upload className="h-4 w-4 mr-2" />
                          Télécharger un PDF
                        </>
                      )}
                    </Button>
                    <p className="text-xs text-gray-500 mt-2">
                      Glissez et déposez un fichier PDF ou cliquez pour sélectionner
                    </p>
                  </div>
                </div>
              )}
              <input
                ref={fileInputRef}
                type="file"
                accept=".pdf,application/pdf"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) handleFileUpload(file);
                }}
                className="hidden"
              />
            </div>
          </div>
        </div>
        </div>

        <div className="border-t p-8 pt-6">
          <div className="flex gap-3 justify-end">
            <Button
              variant="outline"
              onClick={onClose}
              disabled={isLoading}
              className="rounded-2xl px-6"
            >
              Annuler
            </Button>
            <Button
              onClick={handleSubmit}
              disabled={isLoading}
              className="rounded-2xl px-6"
            >
              {isLoading ? (
                <div className="animate-spin rounded-full h-4 w-4 border-2 border-transparent border-t-white mr-2" />
              ) : (
                payslip ? <Save className="h-4 w-4 mr-2" /> : <Plus className="h-4 w-4 mr-2" />
              )}
              {isLoading ? "Sauvegarde..." : (payslip ? "Mettre à jour" : "Créer")}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}