"use client";

import { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table, TableBody, TableCell,
  TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Search, RefreshCw, Trash2, Plus, MapPin,
  Pencil, ArrowLeft, ArrowRight, X,
} from "lucide-react";
import { toast } from "sonner";
import { useCities } from "@/contexts/CitiesContext";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { CityDialog } from "@/components/cities/city-dialog";

const PER_PAGE_OPTIONS = [10, 25, 50];

export default function CitiesPage() {
  const { cities, meta, loading, error, fetchCities, removeCity } = useCities();

  const [q, setQ]                       = useState("");
  const [page, setPage]                 = useState(1);
  const [perPage, setPerPage]           = useState(10);
  const [dialogOpen, setDialogOpen]     = useState(false);
  const [editing, setEditing]           = useState<{ id: number; name: string } | null>(null);
  const [deleteId, setDeleteId]         = useState<number | null>(null);

  useEffect(() => {
    fetchCities({ page, perPage, q });
  }, [fetchCities, page, perPage, q]);

  const openCreate = () => { setEditing(null); setDialogOpen(true); };
  const openEdit   = (city: { id: number; name: string }) => { setEditing(city); setDialogOpen(true); };

  const handleDelete = async () => {
    if (!deleteId) return;
    try {
      await removeCity(deleteId);
      toast.success("Ville supprimée");
      if (cities.length === 1 && page > 1) setPage((p) => p - 1);
    } catch {
      toast.error("Erreur lors de la suppression");
    } finally {
      setDeleteId(null);
    }
  };

  const handleSuccess = () => {
    setDialogOpen(false);
    setEditing(null);
    fetchCities({ page, perPage, q });
  };

  const fmt = (d: string) =>
    new Date(d).toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric" });

  const from = (page - 1) * perPage + 1;
  const to   = Math.min(page * perPage, meta.total);

  return (
    <div className="space-y-5">

      {/* ── Header ── */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Villes</h1>
          <p className="text-sm text-gray-400 mt-0.5">Réseau de villes desservies</p>
        </div>
        <Button
          size="sm"
          onClick={openCreate}
          className="gap-1.5 text-xs bg-rose-600 hover:bg-rose-700 text-white"
        >
          <Plus className="w-3.5 h-3.5" />
          Nouvelle ville
        </Button>
      </div>

      {/* ── Main card ── */}
      <Card className="border border-gray-200 shadow-none bg-white overflow-hidden">

        {/* Toolbar */}
        <CardHeader className="px-6 py-4 border-b border-gray-100">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
              <MapPin className="w-4 h-4 text-rose-500" />
              {meta.total > 0
                ? `${meta.total} ville${meta.total > 1 ? "s" : ""}`
                : "Villes"}
            </CardTitle>

            <div className="flex items-center gap-2">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
                <Input
                  placeholder="Rechercher…"
                  value={q}
                  onChange={(e) => { setQ(e.target.value); setPage(1); }}
                  className="pl-8 h-8 text-xs border-gray-200 w-44"
                />
                {q && (
                  <button
                    onClick={() => { setQ(""); setPage(1); }}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>

              {/* Per page */}
              <select
                value={perPage}
                onChange={(e) => { setPerPage(Number(e.target.value)); setPage(1); }}
                className="h-8 border border-gray-200 rounded-md px-2 text-xs text-gray-600 bg-white focus:outline-none focus:border-gray-300"
              >
                {PER_PAGE_OPTIONS.map((n) => (
                  <option key={n} value={n}>{n} / page</option>
                ))}
              </select>

              <button
                onClick={() => fetchCities({ page, perPage, q })}
                disabled={loading}
                className="p-1.5 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors"
                title="Actualiser"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${loading ? "animate-spin" : ""}`} />
              </button>
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {error ? (
            <div className="flex items-center gap-2 m-6 text-sm text-rose-600 bg-rose-50 border border-rose-200 rounded-lg px-4 py-3">
              <X className="w-4 h-4 flex-shrink-0" />
              {error}
            </div>
          ) : (
            <>
              {/* Table — desktop */}
              <div className="hidden sm:block overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-50 hover:bg-gray-50 border-b border-gray-100">
                      <TableHead className="pl-6 w-16 text-[11px] font-semibold uppercase tracking-wider text-gray-400">ID</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Ville</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Créée le</TableHead>
                      <TableHead className="pr-6 text-right text-[11px] font-semibold uppercase tracking-wider text-gray-400">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      Array.from({ length: perPage > 5 ? 6 : perPage }).map((_, i) => (
                        <TableRow key={i} className="border-b border-gray-100">
                          <TableCell className="pl-6"><Skeleton className="h-3.5 w-8" /></TableCell>
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <Skeleton className="w-8 h-8 rounded-lg" />
                              <Skeleton className="h-3.5 w-32" />
                            </div>
                          </TableCell>
                          <TableCell><Skeleton className="h-3.5 w-20" /></TableCell>
                          <TableCell className="pr-6 text-right"><Skeleton className="h-7 w-16 ml-auto" /></TableCell>
                        </TableRow>
                      ))
                    ) : cities.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="py-14 text-center text-gray-400">
                          <MapPin className="w-7 h-7 mx-auto mb-2 opacity-30" />
                          <p className="text-sm">
                            {q ? `Aucun résultat pour "${q}"` : "Aucune ville enregistrée"}
                          </p>
                        </TableCell>
                      </TableRow>
                    ) : (
                      cities.map((city) => (
                        <TableRow key={city.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                          <TableCell className="pl-6 font-mono text-xs text-gray-400">#{city.id}</TableCell>
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <div className="w-8 h-8 rounded-lg bg-rose-50 flex items-center justify-center flex-shrink-0">
                                <MapPin className="w-3.5 h-3.5 text-rose-500" />
                              </div>
                              <span className="text-sm font-medium text-gray-900">{city.name}</span>
                            </div>
                          </TableCell>
                          <TableCell className="text-xs text-gray-500">{fmt(city.createdAt)}</TableCell>
                          <TableCell className="pr-6">
                            <div className="flex justify-end gap-1">
                              <button
                                onClick={() => openEdit({ id: city.id, name: city.name })}
                                className="p-1.5 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
                                title="Modifier"
                              >
                                <Pencil className="w-3.5 h-3.5" />
                              </button>
                              <button
                                onClick={() => setDeleteId(city.id)}
                                className="p-1.5 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                                title="Supprimer"
                              >
                                <Trash2 className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>

              {/* List — mobile */}
              <div className="sm:hidden divide-y divide-gray-100">
                {loading ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-3 px-5 py-3.5">
                      <Skeleton className="w-9 h-9 rounded-lg flex-shrink-0" />
                      <div className="flex-1 space-y-1.5">
                        <Skeleton className="h-3.5 w-28" />
                        <Skeleton className="h-3 w-16" />
                      </div>
                    </div>
                  ))
                ) : cities.length === 0 ? (
                  <div className="py-12 text-center text-gray-400">
                    <MapPin className="w-7 h-7 mx-auto mb-2 opacity-30" />
                    <p className="text-sm">{q ? `Aucun résultat pour "${q}"` : "Aucune ville"}</p>
                  </div>
                ) : cities.map((city) => (
                  <div key={city.id} className="flex items-center justify-between px-5 py-3.5">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-9 h-9 rounded-lg bg-rose-50 flex items-center justify-center flex-shrink-0">
                        <MapPin className="w-4 h-4 text-rose-500" />
                      </div>
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate">{city.name}</p>
                        <p className="text-[11px] text-gray-400">{fmt(city.createdAt)}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 ml-3 flex-shrink-0">
                      <button
                        onClick={() => openEdit({ id: city.id, name: city.name })}
                        className="p-2 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
                      >
                        <Pencil className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => setDeleteId(city.id)}
                        className="p-2 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination */}
              {meta.total > 0 && (
                <div className="flex items-center justify-between px-6 py-3 border-t border-gray-100">
                  <p className="text-xs text-gray-400">
                    {from}–{to} sur {meta.total}
                  </p>
                  <div className="flex items-center gap-1.5">
                    <Button
                      variant="outline" size="sm"
                      disabled={page === 1 || loading}
                      onClick={() => setPage((p) => p - 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      <ArrowLeft className="w-3 h-3" />
                      Précédent
                    </Button>
                    <Button
                      variant="outline" size="sm"
                      disabled={page === meta.lastPage || loading}
                      onClick={() => setPage((p) => p + 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      Suivant
                      <ArrowRight className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* Dialogs */}
      <CityDialog
        city={editing ?? undefined}
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        onSuccess={handleSuccess}
      />
      <ConfirmDialog
        title="Supprimer la ville ?"
        description="Cette action est irréversible. La ville sera définitivement supprimée."
        open={!!deleteId}
        onOpenChange={(open) => { if (!open) setDeleteId(null); }}
        onConfirm={handleDelete}
      />
    </div>
  );
}
