"use client";

import { useEffect, useState } from "react";
import { Plus, PencilSimple, Trash, MapPin, X, CaretLeft, CaretRight, MagnifyingGlass } from "@phosphor-icons/react";

const PAGE_SIZE = 8;

/* ─── Constants ──────────────────────────────────────────────────── */

interface PointDeVente {
  id:      number;
  name:    string;
  address: string;
  city:    string;
  phone:   string;
  lat:     string;
  lng:     string;
}

const EMPTY_POINT_FORM = { name: "", address: "", city: "", phone: "", lat: "", lng: "" };

type ModalMode = "add" | "edit" | null;

/* ─── Page ───────────────────────────────────────────────────────── */

export default function BoutiquesPage() {
  const [points,        setPoints]        = useState<PointDeVente[]>([]);
  const [pointsLoading, setPointsLoading] = useState(false);
  const [pointModal,    setPointModal]    = useState<ModalMode>(null);
  const [editingPoint,  setEditingPoint]  = useState<PointDeVente | null>(null);
  const [pointForm,     setPointForm]     = useState(EMPTY_POINT_FORM);
  const [savingPoint,   setSavingPoint]   = useState(false);
  const [deletingPoint, setDeletingPoint] = useState<number | null>(null);
  const [page,          setPage]          = useState(1);
  const [search,        setSearch]        = useState("");

  const loadPoints = async () => {
    setPointsLoading(true);
    const res  = await fetch("/api/points-de-vente");
    const data = await res.json();
    setPoints(Array.isArray(data) ? data : []);
    setPointsLoading(false);
  };

  useEffect(() => { loadPoints(); }, []);

  const openAddPoint = () => {
    setEditingPoint(null);
    setPointForm(EMPTY_POINT_FORM);
    setPointModal("add");
  };

  const openEditPoint = (p: PointDeVente) => {
    setEditingPoint(p);
    setPointForm({ name: p.name, address: p.address, city: p.city, phone: p.phone, lat: String(p.lat), lng: String(p.lng) });
    setPointModal("edit");
  };

  const closePointModal = () => {
    setPointModal(null);
    setEditingPoint(null);
  };

  const handleSavePoint = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingPoint(true);
    try {
      const body = { ...pointForm, lat: parseFloat(pointForm.lat), lng: parseFloat(pointForm.lng) };
      if (pointModal === "add") {
        await fetch("/api/points-de-vente", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      } else if (editingPoint) {
        await fetch(`/api/points-de-vente/${editingPoint.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      }
      await loadPoints();
      closePointModal();
    } finally {
      setSavingPoint(false);
    }
  };

  const handleDeletePoint = async (p: PointDeVente) => {
    if (!confirm(`Supprimer "${p.name}" ?`)) return;
    setDeletingPoint(p.id);
    await fetch(`/api/points-de-vente/${p.id}`, { method: "DELETE" });
    await loadPoints();
    setDeletingPoint(null);
  };

  const filtered    = points.filter(p =>
    !search.trim() ||
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    p.city.toLowerCase().includes(search.toLowerCase()) ||
    p.address.toLowerCase().includes(search.toLowerCase())
  );
  const totalPages  = Math.ceil(filtered.length / PAGE_SIZE);
  const pagedPoints = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  return (
    <main className="max-w-5xl mx-auto px-4 py-6 space-y-5">

      {/* Header */}
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-base font-black text-brand-dark" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
            Points de vente
          </h1>
          {!pointsLoading && (
            <p className="text-brand-dark/40 text-xs font-medium mt-0.5">
              {points.length} localisation{points.length !== 1 ? "s" : ""}
            </p>
          )}
        </div>

        <div className="flex items-center gap-2">
          <div className="relative">
            <MagnifyingGlass size={13} weight="bold" className="absolute left-3 top-1/2 -translate-y-1/2 text-brand-dark/35 pointer-events-none" />
            <input
              type="text"
              value={search}
              onChange={e => { setSearch(e.target.value); setPage(1); }}
              placeholder="Nom, ville…"
              className="pl-8 pr-7 py-2 rounded-xl bg-white border border-brand-dark/10 text-xs text-brand-dark placeholder:text-brand-dark/30 focus:outline-none focus:border-brand-dark/30 transition-all w-40"
            />
            {search && (
              <button onClick={() => { setSearch(""); setPage(1); }} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-brand-dark/30 hover:text-brand-dark transition-colors">
                <X size={11} weight="bold" />
              </button>
            )}
          </div>
          <button
            onClick={openAddPoint}
            className="flex items-center gap-1.5 bg-brand-dark text-brand-yellow font-bold px-4 py-2 rounded-full text-xs tracking-wide hover:scale-105 transition-transform duration-200 whitespace-nowrap"
          >
            <Plus size={14} weight="bold" />
            <span>Ajouter</span>
          </button>
        </div>
      </div>

      <div className="space-y-4">
        {pointsLoading ? (
          <div className="text-center py-16 text-brand-dark/40 text-sm">Chargement…</div>
        ) : points.length === 0 ? (
          <div className="text-center py-20 bg-white rounded-3xl border border-brand-dark/8">
            <MapPin size={52} weight="light" className="text-brand-dark/20 mx-auto mb-4" />
            <h3 className="text-base font-bold text-brand-dark mb-1.5">Aucun point de vente</h3>
            <p className="text-brand-dark/40 text-sm mb-6">Ajoutez vos premiers points de vente.</p>
            <button onClick={openAddPoint} className="inline-flex items-center gap-2 bg-brand-dark text-brand-yellow font-bold px-6 py-3 rounded-full text-sm hover:scale-105 transition-transform duration-200">
              <Plus size={15} weight="bold" /> Ajouter un point de vente
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {pagedPoints.map((p) => (
              <div key={p.id} className="bg-white rounded-2xl border border-brand-dark/8 p-5 flex flex-col gap-4">

                {/* Top: icon + actions */}
                <div className="flex items-start justify-between">
                  <div className="w-10 h-10 rounded-xl bg-brand-yellow/20 flex items-center justify-center flex-shrink-0">
                    <MapPin size={18} weight="fill" className="text-brand-dark" />
                  </div>
                  <div className="flex gap-1.5">
                    <button onClick={() => openEditPoint(p)} className="w-8 h-8 flex items-center justify-center rounded-lg border border-brand-dark/12 hover:border-brand-dark/30 hover:bg-brand-dark/5 transition-all text-brand-dark/50 hover:text-brand-dark">
                      <PencilSimple size={13} weight="bold" />
                    </button>
                    <button onClick={() => handleDeletePoint(p)} disabled={deletingPoint === p.id} className="w-8 h-8 flex items-center justify-center rounded-lg border border-red-100 hover:bg-red-50 hover:border-red-200 transition-all text-red-400 disabled:opacity-40">
                      {deletingPoint === p.id ? <span className="w-3 h-3 border border-red-300 border-t-red-500 rounded-full animate-spin" /> : <Trash size={13} weight="bold" />}
                    </button>
                  </div>
                </div>

                {/* Name + city */}
                <div>
                  <h3 className="font-black text-brand-dark text-sm leading-snug" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                    {p.name}
                  </h3>
                  {p.city && (
                    <span className="inline-block mt-1 text-[10px] font-bold px-2 py-0.5 rounded-full bg-brand-dark/6 text-brand-dark/50 uppercase tracking-wide">
                      {p.city}
                    </span>
                  )}
                </div>

                {/* Details */}
                <div className="space-y-1.5 text-xs text-brand-dark/60 border-t border-brand-dark/6 pt-3">
                  {p.address && (
                    <p className="flex items-start gap-1.5">
                      <MapPin size={12} weight="bold" className="flex-shrink-0 mt-0.5 text-brand-dark/30" />
                      {p.address}
                    </p>
                  )}
                  {p.phone && (
                    <p className="flex items-center gap-1.5">
                      <span className="text-brand-dark/30 font-bold">☎</span>
                      {p.phone}
                    </p>
                  )}
                  <p className="text-[10px] text-brand-dark/25 font-mono pt-0.5">
                    {p.lat}, {p.lng}
                  </p>
                </div>

              </div>
            ))}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between pt-2">
            <span className="text-brand-dark/40 text-xs font-semibold">
              Page {page} / {totalPages} — {filtered.length} résultat{filtered.length !== 1 ? "s" : ""}
            </span>
            <div className="flex items-center gap-1.5">
              <button
                onClick={() => setPage(p => Math.max(1, p - 1))}
                disabled={page === 1}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-white border border-brand-dark/10 text-brand-dark/50 hover:text-brand-dark disabled:opacity-30 transition-colors"
              >
                <CaretLeft size={12} weight="bold" />
              </button>
              {Array.from({ length: totalPages }, (_, i) => (
                <button
                  key={i}
                  onClick={() => setPage(i + 1)}
                  className={`w-8 h-8 rounded-xl text-xs font-bold transition-all ${
                    page === i + 1
                      ? "bg-brand-dark text-brand-yellow"
                      : "bg-white border border-brand-dark/10 text-brand-dark/50 hover:text-brand-dark"
                  }`}
                >
                  {i + 1}
                </button>
              ))}
              <button
                onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-white border border-brand-dark/10 text-brand-dark/50 hover:text-brand-dark disabled:opacity-30 transition-colors"
              >
                <CaretRight size={12} weight="bold" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* ─── Point de Vente Modal ──────────────────────────────────── */}
      {pointModal && (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center" onClick={(e) => { if (e.target === e.currentTarget) closePointModal(); }}>
          <div className="absolute inset-0 bg-brand-dark/50 backdrop-blur-sm" />
          <div className="relative w-full sm:max-w-lg bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl max-h-[92dvh] flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-300">
            <div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-brand-dark/8 flex-shrink-0">
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-brand-dark/15 rounded-full sm:hidden" />
              <h2 className="font-bold text-brand-dark" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                {pointModal === "add" ? "Nouveau point de vente" : "Modifier le point de vente"}
              </h2>
              <button type="button" onClick={closePointModal} className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-brand-dark/8 text-brand-dark/50 hover:text-brand-dark transition-colors">
                <X size={16} weight="bold" />
              </button>
            </div>
            <form onSubmit={handleSavePoint} className="overflow-y-auto overscroll-contain flex-1 px-5 py-5 space-y-4" onWheel={(e) => e.stopPropagation()}>
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Nom <span className="text-red-400">*</span></label>
                <input required value={pointForm.name} onChange={(e) => setPointForm((f) => ({ ...f, name: e.target.value }))} placeholder="ex: Supermarché Atlas" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widests uppercase mb-1.5">Ville</label>
                <input value={pointForm.city} onChange={(e) => setPointForm((f) => ({ ...f, city: e.target.value }))} placeholder="ex: Nouakchott" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Adresse</label>
                <input value={pointForm.address} onChange={(e) => setPointForm((f) => ({ ...f, address: e.target.value }))} placeholder="ex: Rue 42, Tevragh Zeina" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Téléphone</label>
                <input value={pointForm.phone} onChange={(e) => setPointForm((f) => ({ ...f, phone: e.target.value }))} placeholder="ex: +222 XX XX XX XX" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Latitude <span className="text-red-400">*</span></label>
                  <input required value={pointForm.lat} onChange={(e) => setPointForm((f) => ({ ...f, lat: e.target.value }))} placeholder="ex: 18.0735" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-brand-dark/50 tracking-widest uppercase mb-1.5">Longitude <span className="text-red-400">*</span></label>
                  <input required value={pointForm.lng} onChange={(e) => setPointForm((f) => ({ ...f, lng: e.target.value }))} placeholder="ex: -15.9582" className="w-full px-4 py-2.5 rounded-xl border border-brand-dark/15 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/25 text-sm text-brand-dark placeholder:text-brand-dark/25 transition-all" />
                </div>
              </div>
              <div className="bg-brand-sand-light rounded-xl px-4 py-3 text-xs text-brand-dark/50">
                Pour trouver les coordonnées : faites un clic droit sur Google Maps → <strong>«&nbsp;Plus d&apos;infos sur cet endroit&nbsp;»</strong> — les coordonnées apparaissent en bas.
              </div>
              <div className="pb-safe">
                <button type="submit" disabled={savingPoint} className="w-full bg-brand-dark text-brand-yellow font-bold py-3.5 rounded-full text-sm tracking-wide flex items-center justify-center gap-2 disabled:opacity-50 hover:scale-[1.01] active:scale-[0.99] transition-transform duration-200 mt-1">
                  {savingPoint && <span className="w-4 h-4 border-2 border-brand-yellow/30 border-t-brand-yellow rounded-full animate-spin" />}
                  {savingPoint ? "Enregistrement..." : pointModal === "add" ? "Ajouter le point de vente" : "Enregistrer les modifications"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </main>
  );
}
