import { useState } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import FormModal, { FormField, FormSection, Input } from "../ui/FormModal";
import { Hash, Truck } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { Commande } from "@/types/commandeTypes";
import { getcommandeSelected } from "@/store/features/commande/selectors";
import { commandeToBL } from "@/store/features/commande/thunk";
import { getBL } from "@/store/features/bl/thunk";
import { selectBL } from "@/store/features/bl/slice";
import { toast } from "../ui/use-toast";
import { Section } from "../ui/Section";
import { formatForDateInput } from "@/lib/utils";
import { BL } from "@/types/BL_Types";
import { ModalLoading } from "./ModalLoading";


export function ModalWorkflowToBL({
  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 handleCreateBL = async () => {
      try {
        setLoadingTransform(true);
        setError(null);
  
        const response = await dispatch(commandeToBL(commande!.numero)).unwrap();
        const res = (await dispatch(getBL(response.document_cible)).unwrap()) as BL;
        dispatch(selectBL(res));
        setLoadingTransform(false);
  
        toast({
          title: 'BL généré avec succès!',
          description: `La commande a été transformée en bon de livraison.`,
          className: 'bg-green-500 text-white border-green-600',
        });
        setTimeout(() => navigate(`/home/bons-livraison/${res.numero}`), 1000);
        onClose()
      } catch (err: any) {
        setLoadingTransform(false);
        setError(err.message);
        toast({
          title: 'Impossible de transformer la commande',
          description: `La commande ${commande.numero} ne peut pas être transformée en BL.`,
          className: 'bg-red-500 text-white border-red-600',
        });
      } finally {
        setLoadingTransform(false);
        onClose()
      }
    };

  if (!open) return null;

  return (
    <FormModal
      isOpen={open}
      onClose={onClose}
      title="Transformer en Bon de Livraison"
      onSubmit={handleCreateBL}
      submitLabel="Générer BL"
    >
      <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">
        <Truck className="w-5 h-5 shrink-0" />
        <p className="text-sm">
          Vous allez générer un Bon de Livraison à partir de la commande <strong>{commande.numero}</strong>.
          <br />
          Les stocks seront mis à jour et la commande passera au statut <strong>Livrée</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">Client</p>
          <p className="font-medium text-gray-900 dark:text-white text-sm">{commande.client_intitule}</p>
        </div>
        <div>
          <p className="text-xs text-gray-500 uppercase font-semibold">Référence</p>
          <p className="font-medium text-gray-900 dark:text-white text-sm">{commande.reference || '-'}</p>
        </div>
      </div>

      <Section title="Détails de l'expédition" icon={Hash} defaultOpen={true}>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Date d'expédition" required>
            <Input
              type="date"
              value={formatForDateInput(commande.date)}
              onChange={e => setDateEmission(e.target.value)}
            />
          </FormField>
          <FormField label="Date de livraison prévue" required>
            <Input type="date" value={dateEmission} onChange={e => setDateEmission(e.target.value)} />
          </FormField>
        </div>
      </Section>

      {(loadingTransform) && <ModalLoading />}
    </FormModal>
  );
}

export default ModalWorkflowToBL;