"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import QRCode from "qrcode";
import {
  ArrowLeft,
  Check,
  ChevronRight,
  CreditCard,
  Loader2,
  MapPin,
  Phone,
  ShoppingBag,
  User,
  WalletCards,
} from "lucide-react";
import {
  useEffect,
  useMemo,
  useState,
} from "react";

import {
  formatPrice,
  useCart,
} from "@/lib/cart";

type OrderType =
  | "RESTAURANT"
  | "TAKEAWAY"
  | "DELIVERY";

type PaymentMethod =
  | "CASH"
  | "WAVE"
  | "ORANGE_MONEY"
  | "MTN_MONEY";

type DeliveryZone = {
  id: string;
  name: string;
  fee: number;
  isActive?: boolean;
  sortOrder?: number;
};

type PaymentAccount = {
  id: string;
  name: string;
  method: PaymentMethod;
  type:
    | "PHONE"
    | "QR_CODE"
    | "API";
  phoneNumber?: string | null;
  accountName?: string | null;
  qrCodeUrl?: string | null;
  apiKey?: string | null;
  isActive?: boolean;
  sortOrder?: number;
};

type PaymentApiMethod = {
  value: PaymentMethod;
  label: string;
  account: PaymentAccount | null;
};

const orderTypes: {
  value: OrderType;
  label: string;
  description: string;
}[] = [
  {
    value: "RESTAURANT",
    label: "Au restaurant",
    description:
      "Je mange directement au restaurant",
  },
  {
    value: "TAKEAWAY",
    label: "À emporter",
    description:
      "Je récupère ma commande au restaurant",
  },
  {
    value: "DELIVERY",
    label: "Livraison",
    description:
      "Je souhaite être livré à mon adresse",
  },
];

const paymentLabels: Record<
  PaymentMethod,
  string
> = {
  CASH: "Espèces",
  WAVE: "Wave",
  ORANGE_MONEY: "Orange Money",
  MTN_MONEY: "MTN Money",
};

const paymentDescriptions: Record<
  PaymentMethod,
  string
> = {
  CASH:
    "Payez directement en espèces.",
  WAVE:
    "Payez rapidement avec votre compte Wave.",
  ORANGE_MONEY:
    "Payez avec Orange Money.",
  MTN_MONEY:
    "Payez avec MTN Money.",
};

export default function CheckoutPage() {
  const router = useRouter();

  const {
    lines,
    clear,
    total: cartSubtotal,
  } = useCart();

  const [
    orderType,
    setOrderType,
  ] = useState<OrderType>(
    "DELIVERY"
  );

  const [
    paymentMethod,
    setPaymentMethod,
  ] =
    useState<PaymentMethod>("WAVE");

  const [
    deliveryZones,
    setDeliveryZones,
  ] = useState<DeliveryZone[]>([]);

  const [
    paymentMethods,
    setPaymentMethods,
  ] = useState<
    PaymentApiMethod[]
  >([]);

  const [
    selectedZoneId,
    setSelectedZoneId,
  ] = useState("");

  const [
    firstName,
    setFirstName,
  ] = useState("");

  const [
    lastName,
    setLastName,
  ] = useState("");

  const [
    phone,
    setPhone,
  ] = useState("");

  const [
    email,
    setEmail,
  ] = useState("");

  const [
    address,
    setAddress,
  ] = useState("");

  const [
    notes,
    setNotes,
  ] = useState("");

  const [
    loading,
    setLoading,
  ] = useState(true);

  const [
    submitting,
    setSubmitting,
  ] = useState(false);

  const [
    error,
    setError,
  ] = useState("");

  const [
    qrCodeDataUrl,
    setQrCodeDataUrl,
  ] = useState("");

  /*
  ============================================================
  CHARGEMENT DES DONNÉES
  ============================================================
  */

  useEffect(() => {
    async function loadData() {
      try {
        setLoading(true);
        setError("");

        const [
          zonesResponse,
          paymentsResponse,
        ] = await Promise.all([
          fetch(
            "/api/delivery-zones",
            {
              cache: "no-store",
            }
          ),
          fetch(
            "/api/payment-methods",
            {
              cache: "no-store",
            }
          ),
        ]);

        const zonesData =
          await zonesResponse.json();

        const paymentsData =
          await paymentsResponse.json();

        if (!zonesResponse.ok) {
          throw new Error(
            zonesData.message ||
              "Impossible de charger les zones de livraison."
          );
        }

        if (!paymentsResponse.ok) {
          throw new Error(
            paymentsData.message ||
              "Impossible de charger les moyens de paiement."
          );
        }

        setDeliveryZones(
          Array.isArray(
            zonesData.zones
          )
            ? zonesData.zones
            : []
        );

        setPaymentMethods(
          Array.isArray(
            paymentsData.methods
          )
            ? paymentsData.methods
            : []
        );
      } catch (error) {
        console.error(
          "Erreur chargement checkout :",
          error
        );

        setError(
          error instanceof Error
            ? error.message
            : "Impossible de charger les informations du checkout."
        );
      } finally {
        setLoading(false);
      }
    }

    loadData();
  }, []);

  /*
  ============================================================
  CALCULS
  ============================================================
  */

  const subtotal = cartSubtotal;

  const selectedZone =
    useMemo(() => {
      return deliveryZones.find(
        (zone) =>
          zone.id ===
          selectedZoneId
      );
    }, [
      deliveryZones,
      selectedZoneId,
    ]);

  const deliveryFee =
    orderType === "DELIVERY"
      ? Number(
          selectedZone?.fee ?? 0
        )
      : 0;

  const total =
    subtotal + deliveryFee;

  /*
  ============================================================
  MOYEN DE PAIEMENT SÉLECTIONNÉ
  ============================================================
  */

  const selectedPaymentMethod =
    useMemo(() => {
      return paymentMethods.find(
        (method) =>
          method.value ===
          paymentMethod
      );
    }, [
      paymentMethods,
      paymentMethod,
    ]);

  const selectedPaymentAccount =
    selectedPaymentMethod?.account ||
    null;

  /*
  ============================================================
  SÉLECTION AUTOMATIQUE DU PAIEMENT
  ============================================================
  */

  useEffect(() => {
    if (
      paymentMethods.length === 0
    ) {
      return;
    }

    const exists =
      paymentMethods.some(
        (method) =>
          method.value ===
          paymentMethod
      );

    if (!exists) {
      setPaymentMethod(
        paymentMethods[0].value
      );
    }
  }, [
    paymentMethods,
    paymentMethod,
  ]);

  /*
  ============================================================
  GÉNÉRATION DU QR CODE
  ============================================================
  */

  useEffect(() => {
    async function generateQrCode() {
      setQrCodeDataUrl("");

      if (
        !selectedPaymentAccount
      ) {
        return;
      }

      if (
        selectedPaymentAccount.type !==
        "QR_CODE"
      ) {
        return;
      }

      if (
        !selectedPaymentAccount.qrCodeUrl
      ) {
        return;
      }

      try {
        const dataUrl =
          await QRCode.toDataURL(
            selectedPaymentAccount.qrCodeUrl,
            {
              width: 320,
              margin: 2,
              errorCorrectionLevel:
                "M",
            }
          );

        setQrCodeDataUrl(
          dataUrl
        );
      } catch (error) {
        console.error(
          "Erreur génération QR Code :",
          error
        );
      }
    }

    generateQrCode();
  }, [
    selectedPaymentAccount,
  ]);

  /*
  ============================================================
  RESET ZONE SI PAS DE LIVRAISON
  ============================================================
  */

  useEffect(() => {
    if (
      orderType !== "DELIVERY"
    ) {
      setSelectedZoneId("");
    }
  }, [orderType]);

  /*
  ============================================================
  SOUMISSION
  ============================================================
  */

async function handleSubmit(
  event: React.FormEvent
) {
  event.preventDefault();

  setError("");

  /*
  ============================================================
  VALIDATION PANIER
  ============================================================
  */

  if (lines.length === 0) {
    setError(
      "Votre panier est vide."
    );

    return;
  }

  /*
  ============================================================
  VALIDATION CLIENT
  ============================================================
  */

  if (!firstName.trim()) {
    setError(
      "Veuillez renseigner votre prénom."
    );

    return;
  }

  if (!lastName.trim()) {
    setError(
      "Veuillez renseigner votre nom."
    );

    return;
  }

  if (!phone.trim()) {
    setError(
      "Veuillez renseigner votre numéro de téléphone."
    );

    return;
  }

  /*
  ============================================================
  VALIDATION LIVRAISON
  ============================================================
  */

  if (
    orderType === "DELIVERY"
  ) {
    if (!selectedZoneId) {
      setError(
        "Veuillez sélectionner une zone de livraison."
      );

      return;
    }

    if (!selectedZone) {
      setError(
        "La zone de livraison sélectionnée est invalide."
      );

      return;
    }

    if (!address.trim()) {
      setError(
        "Veuillez renseigner votre adresse de livraison."
      );

      return;
    }
  }

  /*
  ============================================================
  VALIDATION PAIEMENT
  ============================================================
  */

  if (
    paymentMethod !== "CASH" &&
    !selectedPaymentAccount
  ) {
    setError(
      "Le moyen de paiement sélectionné n'est pas correctement configuré."
    );

    return;
  }

  /*
  ============================================================
  PRÉPARATION DES ARTICLES
  ============================================================
  */

  const orderItems = lines.map(
    (line) => ({
      productId:
        line.item.id,

      productName:
        line.item.name,

      price:
        Number(
          line.item.price
        ),

      quantity:
        Number(
          line.qty
        ),
    })
  );

  /*
  ============================================================
  VÉRIFICATION DES ARTICLES
  ============================================================
  */

  const invalidItem =
    orderItems.some(
      (item) =>
        !item.productId ||
        !item.productName ||
        Number.isNaN(
          item.price
        ) ||
        item.price < 0 ||
        Number.isNaN(
          item.quantity
        ) ||
        item.quantity <= 0
    );

  if (invalidItem) {
    setError(
      "Un ou plusieurs articles de votre panier sont invalides. Veuillez retourner au menu et réessayer."
    );

    return;
  }

  /*
  ============================================================
  ENVOI DE LA COMMANDE
  ============================================================
  */

  try {
    setSubmitting(true);

    const response =
      await fetch(
        "/api/orders",
        {
          method: "POST",

          headers: {
            "Content-Type":
              "application/json",
          },

          body:
            JSON.stringify({
              firstName:
                firstName.trim(),

              lastName:
                lastName.trim(),

              phone:
                phone.trim(),

              email:
                email.trim() ||
                undefined,

              address:
                orderType ===
                "DELIVERY"
                  ? address.trim()
                  : undefined,

              notes:
                notes.trim() ||
                undefined,

              orderType,

              paymentMethod,

              subtotal:
                Number(
                  subtotal
                ),

              deliveryFee:
                Number(
                  deliveryFee
                ),

              total:
                Number(
                  total
                ),

              deliveryZoneId:
                orderType ===
                "DELIVERY"
                  ? selectedZoneId
                  : undefined,

              items:
                orderItems,
            }),
        }
      );

    /*
    ============================================================
    RÉCUPÉRATION DE LA RÉPONSE
    ============================================================
    */

    const data =
      await response.json();

    /*
    ============================================================
    GESTION DES ERREURS API
    ============================================================
    */

    if (!response.ok) {
      throw new Error(
        data.message ||
          "Impossible de créer la commande."
      );
    }

    /*
    ============================================================
    VÉRIFICATION DE LA COMMANDE CRÉÉE
    ============================================================
    */

    if (
      !data.order?.id
    ) {
      throw new Error(
        "La commande a été créée mais son identifiant est introuvable."
      );
    }

    /*
    ============================================================
    SUCCÈS
    ============================================================
    */

    clear();

    router.push(
      `/confirmation/${data.order.id}`
    );
  } catch (error) {
    console.error(
      "Erreur création commande :",
      error
    );

    setError(
      error instanceof Error
        ? error.message
        : "Une erreur est survenue lors de la création de la commande."
    );
  } finally {
    setSubmitting(false);
  }
}


  /*
  ============================================================
  CHARGEMENT
  ============================================================
  */

  if (loading) {
    return (
      <main className="min-h-screen bg-[#f8f6f1]">
        <div className="mx-auto flex min-h-screen max-w-6xl items-center justify-center px-6">
          <div className="text-center">
            <Loader2
              className="mx-auto animate-spin text-[#b8863b]"
              size={34}
            />

            <p className="mt-4 text-sm text-[#6f675e]">
              Préparation de votre commande...
            </p>
          </div>
        </div>
      </main>
    );
  }

  /*
  ============================================================
  PANIER VIDE
  ============================================================
  */

  if (lines.length === 0) {
    return (
      <main className="min-h-screen bg-[#f8f6f1]">
        <div className="mx-auto flex min-h-screen max-w-2xl items-center justify-center px-6 py-16">
          <div className="w-full rounded-3xl border border-[#e8e1d6] bg-white p-8 text-center shadow-sm md:p-12">
            <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-[#f5efe5] text-[#b8863b]">
              <ShoppingBag
                size={28}
              />
            </div>

            <h1 className="mt-6 font-serif text-3xl font-semibold text-[#2f2a24]">
              Votre panier est vide
            </h1>

            <p className="mx-auto mt-3 max-w-md text-sm leading-6 text-[#7a7269]">
              Ajoutez des plats à votre
              panier avant de passer
              votre commande.
            </p>

            <Link
              href="/menu"
              className="mt-8 inline-flex items-center gap-2 rounded-full bg-[#2f2a24] px-6 py-3 text-sm font-semibold text-white transition hover:bg-[#b8863b]"
            >
              Voir le menu

              <ChevronRight
                size={16}
              />
            </Link>
          </div>
        </div>
      </main>
    );
  }

  /*
  ============================================================
  PAGE CHECKOUT
  ============================================================
  */

  return (
    <main className="min-h-screen bg-[#f8f6f1]">
      <header className="border-b border-[#e8e1d6] bg-white">
        <div className="mx-auto flex max-w-7xl items-center justify-between px-6 py-5">
          <Link
            href="/panier"
            className="inline-flex items-center gap-2 text-sm font-medium text-[#5f5a53] transition hover:text-[#b8863b]"
          >
            <ArrowLeft
              size={17}
            />
            Retour au panier
          </Link>

          <div className="text-center">
            <h1 className="font-serif text-2xl font-semibold tracking-wide text-[#2f2a24]">
              Happy Hours
            </h1>

            <p className="mt-1 text-[9px] font-bold uppercase tracking-[0.3em] text-[#b8863b]">
              Finaliser la commande
            </p>
          </div>

          <div className="w-24" />
        </div>
      </header>

      <div className="mx-auto max-w-7xl px-6 py-10 md:py-14">
        <div className="mb-10">
          <p className="text-xs font-bold uppercase tracking-[0.25em] text-[#b8863b]">
            Votre commande
          </p>

          <h2 className="mt-2 font-serif text-4xl font-semibold text-[#2f2a24]">
            Finalisez votre commande
          </h2>

          <p className="mt-3 max-w-2xl text-sm leading-6 text-[#7a7269]">
            Renseignez vos informations,
            choisissez votre mode de
            réception et votre moyen de
            paiement.
          </p>
        </div>

        {error && (
          <div className="mb-8 rounded-2xl border border-red-200 bg-red-50 p-4 text-sm font-medium text-red-700">
            {error}
          </div>
        )}

        <form
          onSubmit={handleSubmit}
          className="grid gap-8 lg:grid-cols-[1fr_400px]"
        >
          <div className="space-y-8">
            {/* TYPE DE COMMANDE */}

            <section className="rounded-3xl border border-[#e8e1d6] bg-white p-6 shadow-sm md:p-8">
              <div className="mb-6">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#b8863b]">
                  Étape 1
                </p>

                <h3 className="mt-2 font-serif text-2xl font-semibold text-[#2f2a24]">
                  Comment souhaitez-vous recevoir votre commande ?
                </h3>
              </div>

              <div className="grid gap-4 md:grid-cols-3">
                {orderTypes.map(
                  (type) => {
                    const active =
                      orderType ===
                      type.value;

                    return (
                      <button
                        key={
                          type.value
                        }
                        type="button"
                        onClick={() =>
                          setOrderType(
                            type.value
                          )
                        }
                        className={`relative rounded-2xl border p-5 text-left transition ${
                          active
                            ? "border-[#b8863b] bg-[#f9f4eb] shadow-sm"
                            : "border-[#e8e1d6] hover:border-[#d8c19a] hover:bg-[#fcfaf7]"
                        }`}
                      >
                        {active && (
                          <span className="absolute right-4 top-4 flex h-6 w-6 items-center justify-center rounded-full bg-[#b8863b] text-white">
                            <Check
                              size={14}
                            />
                          </span>
                        )}

                        <span className="block text-sm font-semibold text-[#2f2a24]">
                          {
                            type.label
                          }
                        </span>

                        <span className="mt-2 block text-xs leading-5 text-[#81786e]">
                          {
                            type.description
                          }
                        </span>
                      </button>
                    );
                  }
                )}
              </div>
            </section>

            {/* INFORMATIONS CLIENT */}

            <section className="rounded-3xl border border-[#e8e1d6] bg-white p-6 shadow-sm md:p-8">
              <div className="mb-6">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#b8863b]">
                  Étape 2
                </p>

                <h3 className="mt-2 font-serif text-2xl font-semibold text-[#2f2a24]">
                  Vos informations
                </h3>
              </div>

              <div className="grid gap-5 md:grid-cols-2">
                <FormInput
                  label="Prénom"
                  value={firstName}
                  onChange={
                    setFirstName
                  }
                  placeholder="Votre prénom"
                  icon={
                    <User
                      size={16}
                    />
                  }
                  required
                />

                <FormInput
                  label="Nom"
                  value={lastName}
                  onChange={
                    setLastName
                  }
                  placeholder="Votre nom"
                  required
                />

                <FormInput
                  label="Téléphone"
                  value={phone}
                  onChange={setPhone}
                  placeholder="07 00 00 00 00"
                  icon={
                    <Phone
                      size={16}
                    />
                  }
                  required
                />

                <FormInput
                  label="Email"
                  type="email"
                  value={email}
                  onChange={setEmail}
                  placeholder="votre@email.com"
                />

                {orderType ===
                  "DELIVERY" && (
                  <>
                    <div className="md:col-span-2">
  <label className="mb-3 block text-sm font-semibold text-[#403a33]">
    Zone de livraison
    <span className="ml-1 text-[#b8863b]">*</span>
  </label>

  <div className="relative">
    {/* Icône */}
    <div className="pointer-events-none absolute left-4 top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-xl bg-[#f8f1e6] text-[#b8863b]">
      <MapPin size={18} />
    </div>

    {/* Sélection */}
    <select
      value={selectedZoneId}
      onChange={(event) =>
        setSelectedZoneId(event.target.value)
      }
      required
      className={`w-full appearance-none rounded-2xl border bg-white py-4 pl-[4.5rem] pr-14 text-sm font-medium outline-none transition-all duration-200 ${
        selectedZoneId
          ? "border-[#c9a15b] bg-[#fffdf9] text-[#2f2a24] shadow-[0_4px_20px_rgba(184,134,59,0.08)]"
          : "border-[#e8e1d6] text-[#91887d]"
      } hover:border-[#d8c19a] focus:border-[#b8863b] focus:ring-4 focus:ring-[#b8863b]/10`}
    >
      <option value="">
        Sélectionnez votre zone de livraison
      </option>

      {deliveryZones.map((zone) => (
        <option
          key={zone.id}
          value={zone.id}
        >
          {zone.name} — {formatPrice(zone.fee)}
        </option>
      ))}
    </select>

    {/* Flèche */}
    <div className="pointer-events-none absolute right-4 top-1/2 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full bg-[#f8f1e6] text-[#a68b5b]">
      <ChevronRight
        size={17}
        className="rotate-90"
      />
    </div>
  </div>

  {/* Informations sur la zone sélectionnée */}
  {selectedZone && (
    <div className="mt-3 flex items-center justify-between rounded-2xl border border-[#eee4d5] bg-[#fcfaf6] px-4 py-3">
      <div className="flex items-center gap-3">
        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-[#f3eadc] text-[#b8863b]">
          <MapPin size={15} />
        </div>

        <div>
          <p className="text-[11px] font-medium uppercase tracking-[0.12em] text-[#a68b5b]">
            Livraison vers
          </p>

          <p className="mt-0.5 text-sm font-semibold text-[#2f2a24]">
            {selectedZone.name}
          </p>
        </div>
      </div>

      <div className="text-right">
        <p className="text-[11px] font-medium uppercase tracking-[0.12em] text-[#a68b5b]">
          Frais
        </p>

        <p className="mt-0.5 text-sm font-bold text-[#b8863b]">
          {formatPrice(selectedZone.fee)}
        </p>
      </div>
    </div>
  )}

  {!selectedZoneId && (
    <p className="mt-2 text-xs text-[#968d82]">
      Sélectionnez votre zone afin de calculer automatiquement les frais de livraison.
    </p>
  )}
</div>

                    <div className="md:col-span-2">
                      <FormInput
                        label="Adresse de livraison"
                        value={
                          address
                        }
                        onChange={
                          setAddress
                        }
                        placeholder="Quartier, rue, repère..."
                        icon={
                          <MapPin
                            size={16}
                          />
                        }
                        required
                      />
                    </div>
                  </>
                )}

                <div className="md:col-span-2">
                  <label className="mb-2 block text-sm font-semibold text-[#403a33]">
                    Note pour la commande

                    <span className="ml-2 font-normal text-gray-400">
                      (facultatif)
                    </span>
                  </label>

                  <textarea
                    value={notes}
                    onChange={(event) =>
                      setNotes(
                        event.target
                          .value
                      )
                    }
                    rows={4}
                    placeholder="Une précision concernant votre commande..."
                    className="w-full resize-none rounded-xl border border-[#e8e1d6] bg-white px-4 py-3.5 text-sm text-[#2f2a24] outline-none transition placeholder:text-gray-400 focus:border-[#b8863b] focus:ring-2 focus:ring-[#b8863b]/10"
                  />
                </div>
              </div>
            </section>

            {/* PAIEMENT */}

            <section className="rounded-3xl border border-[#e8e1d6] bg-white p-6 shadow-sm md:p-8">
              <div className="mb-6">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#b8863b]">
                  Étape 3
                </p>

                <h3 className="mt-2 font-serif text-2xl font-semibold text-[#2f2a24]">
                  Choisissez votre moyen de paiement
                </h3>
              </div>

              {paymentMethods.length ===
              0 ? (
                <div className="rounded-2xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-800">
                  Aucun moyen de paiement
                  n'est actuellement
                  configuré. Veuillez
                  contacter le restaurant.
                </div>
              ) : (
                <div className="grid gap-3 md:grid-cols-2">
                  {paymentMethods.map(
                    (method) => {
                      const active =
                        paymentMethod ===
                        method.value;

                      return (
                        <button
                          key={
                            method.value
                          }
                          type="button"
                          onClick={() =>
                            setPaymentMethod(
                              method.value
                            )
                          }
                          className={`relative rounded-2xl border p-5 text-left transition ${
                            active
                              ? "border-[#b8863b] bg-[#f9f4eb]"
                              : "border-[#e8e1d6] hover:border-[#d8c19a]"
                          }`}
                        >
                          <div className="flex items-start gap-4">
                            <div
                              className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-xl ${
                                active
                                  ? "bg-[#b8863b] text-white"
                                  : "bg-[#f5efe5] text-[#a68b5b]"
                              }`}
                            >
                              {method.value ===
                              "CASH" ? (
                                <WalletCards
                                  size={
                                    20
                                  }
                                />
                              ) : (
                                <CreditCard
                                  size={
                                    20
                                  }
                                />
                              )}
                            </div>

                            <div className="min-w-0">
                              <p className="text-sm font-semibold text-[#2f2a24]">
                                {
                                  method.label
                                }
                              </p>

                              <p className="mt-1 text-xs leading-5 text-[#81786e]">
                                {
                                  paymentDescriptions[
                                    method.value
                                  ]
                                }
                              </p>
                            </div>

                            {active && (
                              <span className="ml-auto flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#b8863b] text-white">
                                <Check
                                  size={
                                    14
                                  }
                                />
                              </span>
                            )}
                          </div>
                        </button>
                      );
                    }
                  )}
                </div>
              )}

              {paymentMethod !==
                "CASH" &&
                selectedPaymentAccount && (
                  <div className="mt-6 rounded-2xl border border-[#e8e1d6] bg-[#fcfaf7] p-6">
                    <div className="flex flex-col gap-6 md:flex-row">
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-bold uppercase tracking-[0.18em] text-[#b8863b]">
                          Informations de paiement
                        </p>

                        <h4 className="mt-2 text-lg font-semibold text-[#2f2a24]">
                          {
                            selectedPaymentAccount.name
                          }
                        </h4>

                        {selectedPaymentAccount.accountName && (
                          <p className="mt-3 text-sm text-[#5f5a53]">
                            <span className="font-semibold">
                              Titulaire :
                            </span>{" "}
                            {
                              selectedPaymentAccount.accountName
                            }
                          </p>
                        )}

                        {selectedPaymentAccount.phoneNumber && (
                          <p className="mt-2 text-sm text-[#5f5a53]">
                            <span className="font-semibold">
                              Numéro :
                            </span>{" "}
                            {
                              selectedPaymentAccount.phoneNumber
                            }
                          </p>
                        )}

                        {selectedPaymentAccount.type ===
                          "QR_CODE" &&
                          selectedPaymentAccount.qrCodeUrl && (
                            <div className="mt-5">
                              <p className="mb-3 text-sm font-semibold text-[#2f2a24]">
                                Scannez ce QR Code pour payer
                              </p>

                              {qrCodeDataUrl ? (
                                <div className="inline-flex rounded-2xl border border-[#e8e1d6] bg-white p-4 shadow-sm">
                                  <img
                                    src={
                                      qrCodeDataUrl
                                    }
                                    alt="QR Code de paiement"
                                    className="h-56 w-56"
                                  />
                                </div>
                              ) : (
                                <div className="flex h-56 w-56 items-center justify-center rounded-2xl border border-[#e8e1d6] bg-white">
                                  <Loader2
                                    className="animate-spin text-[#b8863b]"
                                    size={
                                      28
                                    }
                                  />
                                </div>
                              )}

                              <p className="mt-3 max-w-sm text-xs leading-5 text-[#81786e]">
                                Scannez le QR
                                Code avec votre
                                application de
                                paiement.
                              </p>

                              <a
                                href={
                                  selectedPaymentAccount.qrCodeUrl
                                }
                                target="_blank"
                                rel="noopener noreferrer"
                                className="mt-4 inline-flex items-center justify-center rounded-full border border-[#d8c19a] px-5 py-2.5 text-xs font-semibold text-[#a68b5b] transition hover:bg-[#f5efe5]"
                              >
                                Ouvrir le lien de paiement
                              </a>
                            </div>
                          )}

                        {selectedPaymentAccount.type ===
                          "PHONE" &&
                          selectedPaymentAccount.phoneNumber && (
                            <div className="mt-5 rounded-xl bg-[#f5efe5] p-4">
                              <p className="text-xs text-[#81786e]">
                                Effectuez le paiement sur ce numéro :
                              </p>

                              <p className="mt-1 text-lg font-bold text-[#2f2a24]">
                                {
                                  selectedPaymentAccount.phoneNumber
                                }
                              </p>
                            </div>
                          )}
                      </div>

                      <div className="md:w-56">
                        <div className="rounded-2xl bg-[#f5efe5] p-5">
                          <p className="text-xs text-[#81786e]">
                            Montant à payer
                          </p>

                          <p className="mt-2 text-2xl font-bold text-[#2f2a24]">
                            {formatPrice(
                              total
                            )}
                          </p>

                          <p className="mt-3 text-xs leading-5 text-[#81786e]">
                            Effectuez le
                            paiement avec les
                            informations
                            affichées avant de
                            finaliser votre
                            commande.
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
            </section>
          </div>

          {/* RÉCAPITULATIF */}

          <aside className="lg:sticky lg:top-8 lg:self-start">
            <div className="overflow-hidden rounded-3xl border border-[#e8e1d6] bg-white shadow-sm">
              <div className="border-b border-[#eee8df] p-6">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#b8863b]">
                  Récapitulatif
                </p>

                <h3 className="mt-2 font-serif text-2xl font-semibold text-[#2f2a24]">
                  Votre commande
                </h3>
              </div>

              <div className="max-h-[360px] space-y-4 overflow-y-auto p-6">
                {lines.map(
                  (line) => (
                    <div
                      key={
                        line.item.id
                      }
                      className="flex gap-4"
                    >
                      <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-[#f5efe5] text-sm font-bold text-[#a68b5b]">
                        ×
                        {
                          line.qty
                        }
                      </div>

                      <div className="min-w-0 flex-1">
                        <p className="truncate text-sm font-semibold text-[#2f2a24]">
                          {
                            line.item.name
                          }
                        </p>

                        <p className="mt-1 text-xs text-[#81786e]">
                          {formatPrice(
                            line.item.price
                          )}{" "}
                          ×{" "}
                          {
                            line.qty
                          }
                        </p>
                      </div>

                      <p className="shrink-0 text-sm font-semibold text-[#2f2a24]">
                        {formatPrice(
                          line.item.price *
                            line.qty
                        )}
                      </p>
                    </div>
                  )
                )}
              </div>

              <div className="border-t border-[#eee8df] p-6">
                <div className="space-y-3 text-sm">
                  <div className="flex justify-between gap-4 text-[#6f675e]">
                    <span>
                      Sous-total
                    </span>

                    <span className="font-medium text-[#2f2a24]">
                      {formatPrice(
                        subtotal
                      )}
                    </span>
                  </div>

                  <div className="flex justify-between gap-4 text-[#6f675e]">
                    <span>
                      Livraison
                    </span>

                    <span className="font-medium text-[#2f2a24]">
                      {deliveryFee >
                      0
                        ? formatPrice(
                            deliveryFee
                          )
                        : "Gratuite"}
                    </span>
                  </div>
                </div>

                <div className="my-5 border-t border-dashed border-[#ddd4c8]" />

                <div className="flex items-end justify-between gap-4">
                  <span className="text-sm font-semibold text-[#5f5a53]">
                    Total
                  </span>

                  <span className="font-serif text-2xl font-bold text-[#2f2a24]">
                    {formatPrice(
                      total
                    )}
                  </span>
                </div>

                <button
                  type="submit"
                  disabled={
                    submitting
                  }
                  className="mt-6 flex w-full items-center justify-center gap-2 rounded-full bg-[#2f2a24] px-6 py-4 text-sm font-semibold text-white transition hover:bg-[#b8863b] disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {submitting ? (
                    <>
                      <Loader2
                        size={18}
                        className="animate-spin"
                      />
                      Création de la commande...
                    </>
                  ) : (
                    <>
                      Confirmer la commande

                      <ChevronRight
                        size={18}
                      />
                    </>
                  )}
                </button>

                <p className="mt-4 text-center text-[11px] leading-5 text-[#968d82]">
                  En confirmant votre
                  commande, vous acceptez
                  que les informations
                  fournies soient utilisées
                  pour le traitement de votre
                  commande.
                </p>
              </div>
            </div>
          </aside>
        </form>
      </div>
    </main>
  );
}

/*
============================================================
COMPOSANT INPUT
============================================================
*/

function FormInput({
  label,
  value,
  onChange,
  placeholder,
  type = "text",
  icon,
  required = false,
}: {
  label: string;
  value: string;
  onChange: (
    value: string
  ) => void;
  placeholder?: string;
  type?: string;
  icon?: React.ReactNode;
  required?: boolean;
}) {
  return (
    <div>
      <label className="mb-2 block text-sm font-semibold text-[#403a33]">
        {label}

        {required && (
          <span className="ml-1 text-[#b8863b]">
            *
          </span>
        )}
      </label>

      <div className="relative">
        {icon && (
          <span className="absolute left-4 top-1/2 -translate-y-1/2 text-[#a68b5b]">
            {icon}
          </span>
        )}

        <input
          type={type}
          value={value}
          onChange={(event) =>
            onChange(
              event.target.value
            )
          }
          placeholder={placeholder}
          required={required}
          className={`w-full rounded-xl border border-[#e8e1d6] bg-white py-3.5 text-sm text-[#2f2a24] outline-none transition placeholder:text-gray-400 focus:border-[#b8863b] focus:ring-2 focus:ring-[#b8863b]/10 ${
            icon
              ? "pl-11 pr-4"
              : "px-4"
          }`}
        />
      </div>
    </div>
  );
}