import { useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import FormModal, { FormField, Input } from "../ui/FormModal";
import { FileText, Hash } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { Commande } from "@/types/commandeTypes";
import { getcommandeSelected } from "@/store/features/commande/selectors";
import { commandeToFacture } from "@/store/features/commande/thunk";
import { toast } from "../ui/use-toast";
import { Section } from "../ui/Section";
import { formatForDateInput } from "@/lib/utils";
import { ModalLoading } from "./ModalLoading";
import { getFacture } from "@/store/features/factures/thunk";
import { selectfacture } from "@/store/features/factures/slice";


export function ModalCommandetoFacture({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();


  const [dateEmission, setDateEmission] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() + 29);
    return d.toISOString().split('T')[0];
  });

  
  const commande = useAppSelector(getcommandeSelected) as Commande;
  const [loadingTransform, setLoadingTransform] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleCreateFacture = async () => {
    try {
      setLoadingTransform(true);
      setError(null);

      const response = await dispatch(commandeToFacture(commande!.numero)).unwrap();
      const res = await dispatch(getFacture(response.document_cible)).unwrap();
      dispatch(selectfacture(res));
      setLoadingTransform(false);

      toast({
        title: 'Facture générée avec succès!',
        description: `La commande ${commande.numero} a été transformée en facture.`,
        className: 'bg-green-500 text-white border-green-600',
      });
      setTimeout(() => navigate(`/home/factures/${res.numero}`), 1000);
    } catch (err: any) {
      onClose();
      setLoadingTransform(false);
      setError(err.message);
      toast({
        title: 'Impossible de transformer la commande',
        description: `La commande ${commande.numero} ne peut pas être transformée en facture.`,
        className: 'bg-red-500 text-white border-red-600',
      });
    } finally {
      setLoadingTransform(false);
    }
  };

  if (!open) return null;

  return (
      <FormModal
        isOpen={open}
        onClose={onClose}
        title="Générer la Facture"
        onSubmit={handleCreateFacture}
      >
        <div className="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-200 rounded-xl text-sm flex gap-3 border border-blue-100 dark:border-blue-800">
          <FileText className="w-5 h-5 shrink-0" />
          <p className="text-sm">
            Vous allez générer une facture client basée sur la commande <strong>{commande.numero}</strong>.
            <br />
            La commande passera au statut <strong>Transformée en facture.</strong>
          </p>
        </div>

        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4 mb-6 grid grid-cols-2 gap-4">
          <div>
            <p className="text-xs text-gray-500 uppercase font-semibold">Montant HT</p>
            <p className="font-medium text-gray-900 dark:text-white text-sm">{commande.total_ht.toFixed(2)} €</p>
          </div>
          <div>
            <p className="text-xs text-gray-500 uppercase font-semibold">Montant TTC</p>
            <p className="font-medium text-gray-900 dark:text-white text-sm">{commande.total_ttc.toFixed(2) || '-'} €</p>
          </div>
        </div>

        <Section title="Paramètres de facturation" icon={Hash} defaultOpen={true}>
          <div className="grid grid-cols-2 gap-4">
            <FormField label="Date de la facture" required>
              <Input
                type="date"
                value={formatForDateInput(commande.date)}
                onChange={e => setDateEmission(e.target.value)}
              />
            </FormField>
            <FormField label="Date d'échéance" required>
              <Input type="date" value={dateEmission} onChange={e => setDateEmission(e.target.value)} />
            </FormField>
          </div>
        </Section>

        {(loadingTransform) && <ModalLoading />}

      </FormModal>
  );
}

export default ModalCommandetoFacture;