"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Image from "next/image";
import { CheckCircle2, Ban } from "lucide-react";
import Button from "@/components/Button";
import ConfirmDialog from "@/components/admin/ui/ConfirmDialog";
import { useAuthHydrated } from "@/store/useAuthHydrated";
import { useAuthStore } from "@/store/auth";
import { getCommande, annulerCommande } from "@/lib/api/commandes";
import { urlAsset } from "@/lib/utils/assets";
import type { Commande } from "@/types/commande";
import styles from "./page.module.css";

const STATUT_LABELS: Record<string, string> = {
  EN_ATTENTE: "En attente de paiement",
  VALIDEE: "Validée",
  EN_PRODUCTION: "En production",
  LIVREE: "Livrée",
  ANNULEE: "Annulée",
};

export default function DetailCommandePage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const hydrate = useAuthHydrated();
  const user = useAuthStore((state) => state.user);

  const [commande, setCommande] = useState<Commande | null>(null);
  const [chargement, setChargement] = useState(true);
  const [erreur, setErreur] = useState(false);
  const [confirmAnnulation, setConfirmAnnulation] = useState(false);
  const [annulationEnCours, setAnnulationEnCours] = useState(false);

  useEffect(() => {
    if (!hydrate || !user) return;
    getCommande(params.id)
      .then(setCommande)
      .catch(() => setErreur(true))
      .finally(() => setChargement(false));
  }, [hydrate, user, params.id]);

  const executerAnnulation = async () => {
    if (!commande) return;
    setAnnulationEnCours(true);
    try {
      await annulerCommande(commande.uid);
      setCommande({ ...commande, statut: "ANNULEE" });
      setConfirmAnnulation(false);
    } finally {
      setAnnulationEnCours(false);
    }
  };

  if (!hydrate || (user && chargement)) {
    return (
      <main className={styles.page}>
        <p className={styles.chargement}>Chargement...</p>
      </main>
    );
  }

  if (!user) {
    return (
      <main className={styles.page}>
        <div className={styles.centre}>
          <h1>Connectez-vous pour voir cette commande</h1>
          <Button href="/auth/connexion" size="lg">
            Se connecter
          </Button>
        </div>
      </main>
    );
  }

  if (erreur || !commande) {
    return (
      <main className={styles.page}>
        <div className={styles.centre}>
          <h1>Commande introuvable</h1>
          <Button href="/commandes" size="lg">
            Voir mes commandes
          </Button>
        </div>
      </main>
    );
  }

  return (
    <main className={styles.page}>
      <div className={styles.inner}>
        {commande.statut === "EN_ATTENTE" && (
          <div className={styles.bandeauConfirmation}>
            <CheckCircle2 size={20} />
            <span>
              Votre commande a bien été enregistrée. Un membre de l&apos;équipe Pubago vous
              contactera pour confirmer le paiement Mobile Money.
            </span>
          </div>
        )}

        <div className={styles.enTete}>
          <div>
            <span className={styles.reference}>{commande.reference}</span>
            <h1 className={styles.titre}>{commande.produit.nom}</h1>
          </div>
          <span className={styles.statut} data-statut={commande.statut}>
            {STATUT_LABELS[commande.statut] ?? commande.statut}
          </span>
        </div>

        <div className={styles.carte}>
          {commande.produit.imageUrl && (
            <div className={styles.imageProduit}>
              <Image
                src={urlAsset(commande.produit.imageUrl)}
                alt={commande.produit.nom}
                fill
                sizes="160px"
                className={styles.image}
              />
            </div>
          )}
          <dl className={styles.details}>
            <div>
              <dt>Quantité</dt>
              <dd>{commande.quantite.toLocaleString("fr-FR")}</dd>
            </div>
            <div>
              <dt>Montant total</dt>
              <dd>{commande.montantTotal.toLocaleString("fr-FR")} FCFA</dd>
            </div>
            <div>
              <dt>Mode de paiement</dt>
              <dd>{commande.modePaiement.replace("_", " ")}</dd>
            </div>
            <div>
              <dt>Date</dt>
              <dd>{new Date(commande.createdAt).toLocaleDateString("fr-FR")}</dd>
            </div>
          </dl>
        </div>

        {commande.noteClient && (
          <div className={styles.note}>
            <span>Votre note</span>
            <p>{commande.noteClient}</p>
          </div>
        )}

        <div className={styles.actions}>
          <Button href="/commandes" variant="secondaire">
            Voir mes commandes
          </Button>
          {commande.statut === "EN_ATTENTE" && (
            <Button variant="secondaire" onClick={() => setConfirmAnnulation(true)} icone={<Ban size={16} />}>
              Annuler la commande
            </Button>
          )}
        </div>
      </div>

      <ConfirmDialog
        open={confirmAnnulation}
        title="Annuler cette commande ?"
        description="Cette action est irréversible."
        confirmLabel="Annuler la commande"
        danger
        onConfirm={executerAnnulation}
        onCancel={() => setConfirmAnnulation(false)}
      />
    </main>
  );
}
