"use client";

import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { Product } from "@/lib/supabase/types";

export interface CartLine {
  id: string; // local id (uuid client-side)
  product: Product;
  quantite: number;
  numero_cle_grave: string;
  has_carte_proprio: boolean;
  // documents par type, stockés en base64 dataURL (uploadés à la soumission)
  documents: Record<string, { name: string; dataUrl: string }>;
}

interface CartState {
  lines: CartLine[];
  addLine: (product: Product) => string;
  updateLine: (id: string, patch: Partial<CartLine>) => void;
  removeLine: (id: string) => void;
  setDocument: (lineId: string, type: string, file: { name: string; dataUrl: string }) => void;
  removeDocument: (lineId: string, type: string) => void;
  clear: () => void;
  total: () => number;
}

function uid() {
  return Math.random().toString(36).slice(2) + Date.now().toString(36);
}

export const useCart = create<CartState>()(
  persist(
    (set, get) => ({
      lines: [],
      addLine: (product) => {
        const id = uid();
        set((s) => ({
          lines: [
            ...s.lines,
            {
              id,
              product,
              quantite: 1,
              numero_cle_grave: "",
              has_carte_proprio: false,
              documents: {},
            },
          ],
        }));
        return id;
      },
      updateLine: (id, patch) =>
        set((s) => ({
          lines: s.lines.map((l) => (l.id === id ? { ...l, ...patch } : l)),
        })),
      removeLine: (id) =>
        set((s) => ({ lines: s.lines.filter((l) => l.id !== id) })),
      setDocument: (lineId, type, file) =>
        set((s) => ({
          lines: s.lines.map((l) =>
            l.id === lineId ? { ...l, documents: { ...l.documents, [type]: file } } : l
          ),
        })),
      removeDocument: (lineId, type) =>
        set((s) => ({
          lines: s.lines.map((l) => {
            if (l.id !== lineId) return l;
            const docs = { ...l.documents };
            delete docs[type];
            return { ...l, documents: docs };
          }),
        })),
      clear: () => set({ lines: [] }),
      total: () =>
        get().lines.reduce(
          (sum, l) => sum + (l.product.prix_ht ?? 0) * l.quantite,
          0
        ),
    }),
    { name: "mcb-cart" }
  )
);
