"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,
  Building2, ArrowLeft, ArrowRight, X,
} from "lucide-react";
import { toast } from "sonner";
import Image from "next/image";
import { useCompanies } from "@/contexts/CompaniesContext";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { CompanyDialog } from "@/components/companies/company-dialog";

const PER_PAGE_OPTIONS = [10, 25, 50];
const API_URL = process.env.NEXT_PUBLIC_API_URL ?? "https://bus-two-backend.sapsapticket.com";

export default function CompaniesPage() {
  const { companies, meta, loading, error, fetchCompanies, removeCompany } = useCompanies();

  const [q, setQ]         = useState("");
  const [page, setPage]   = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [deleteId, setDeleteId] = useState<number | null>(null);

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

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

  const refresh = () => fetchCompanies({ 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">Compagnies</h1>
          <p className="text-sm text-gray-400 mt-0.5">Compagnies de transport partenaires</p>
        </div>
        <CompanyDialog onSuccess={refresh} />
      </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">
              <Building2 className="w-4 h-4 text-rose-500" />
              {meta.total > 0
                ? `${meta.total} compagnie${meta.total > 1 ? "s" : ""}`
                : "Compagnies"}
            </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={refresh}
                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 text-[11px] font-semibold uppercase tracking-wider text-gray-400">Compagnie</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">N° Enregistrement</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 && companies.length === 0 ? (
                      Array.from({ length: perPage > 5 ? 6 : perPage }).map((_, i) => (
                        <TableRow key={i} className="border-b border-gray-100">
                          <TableCell className="pl-6">
                            <div className="flex items-center gap-3">
                              <Skeleton className="w-9 h-9 rounded-lg flex-shrink-0" />
                              <div className="space-y-1.5">
                                <Skeleton className="h-3.5 w-32" />
                                <Skeleton className="h-3 w-10" />
                              </div>
                            </div>
                          </TableCell>
                          <TableCell><Skeleton className="h-5 w-24 rounded-md" /></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>
                      ))
                    ) : companies.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="py-14 text-center text-gray-400">
                          <Building2 className="w-7 h-7 mx-auto mb-2 opacity-30" />
                          <p className="text-sm">
                            {q ? `Aucun résultat pour "${q}"` : "Aucune compagnie enregistrée"}
                          </p>
                        </TableCell>
                      </TableRow>
                    ) : (
                      companies.map((company) => (
                        <TableRow key={company.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                          <TableCell className="pl-6">
                            <div className="flex items-center gap-3">
                              {company.logoUrl ? (
                                <Image
                                  src={`${API_URL}/${company.logoUrl}`}
                                  alt={company.name}
                                  width={36}
                                  height={36}
                                  className="rounded-lg object-cover border border-gray-200 flex-shrink-0"
                                />
                              ) : (
                                <div className="w-9 h-9 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                                  <Building2 className="w-4 h-4 text-gray-400" />
                                </div>
                              )}
                              <div className="min-w-0">
                                <p className="text-sm font-medium text-gray-900 truncate">{company.name}</p>
                                <p className="text-[11px] text-gray-400">#{company.id}</p>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell>
                            <span className="inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-medium bg-gray-50 text-gray-600 border border-gray-200">
                              {company.registrationNumber}
                            </span>
                          </TableCell>
                          <TableCell className="text-xs text-gray-500">{fmt(company.createdAt)}</TableCell>
                          <TableCell className="pr-6">
                            <div className="flex justify-end gap-1">
                              <CompanyDialog
                                company={{
                                  id: company.id,
                                  name: company.name,
                                  registrationNumber: company.registrationNumber,
                                  logo_url: company.logoUrl,
                                }}
                                onSuccess={refresh}
                              />
                              <button
                                onClick={() => setDeleteId(company.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 && companies.length === 0 ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-3 px-5 py-3.5">
                      <Skeleton className="w-10 h-10 rounded-lg flex-shrink-0" />
                      <div className="flex-1 space-y-1.5">
                        <Skeleton className="h-3.5 w-32" />
                        <Skeleton className="h-3 w-20" />
                      </div>
                    </div>
                  ))
                ) : companies.length === 0 ? (
                  <div className="py-12 text-center text-gray-400">
                    <Building2 className="w-7 h-7 mx-auto mb-2 opacity-30" />
                    <p className="text-sm">{q ? `Aucun résultat pour "${q}"` : "Aucune compagnie"}</p>
                  </div>
                ) : companies.map((company) => (
                  <div key={company.id} className="flex items-center justify-between px-5 py-3.5">
                    <div className="flex items-center gap-3 min-w-0">
                      {company.logoUrl ? (
                        <Image
                          src={`${API_URL}/${company.logoUrl}`}
                          alt={company.name}
                          width={40}
                          height={40}
                          className="rounded-lg object-cover border border-gray-200 flex-shrink-0"
                        />
                      ) : (
                        <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                          <Building2 className="w-4 h-4 text-gray-400" />
                        </div>
                      )}
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate">{company.name}</p>
                        <p className="text-[11px] text-gray-400">{company.registrationNumber}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 ml-3 flex-shrink-0">
                      <CompanyDialog
                        company={{
                          id: company.id,
                          name: company.name,
                          registrationNumber: company.registrationNumber,
                          logo_url: company.logoUrl,
                        }}
                        onSuccess={refresh}
                      />
                      <button
                        onClick={() => setDeleteId(company.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>

      <ConfirmDialog
        title="Supprimer la compagnie ?"
        description="Cette action est irréversible. La compagnie sera définitivement supprimée du système."
        open={!!deleteId}
        onOpenChange={(open) => { if (!open) setDeleteId(null); }}
        onConfirm={handleDelete}
      />
    </div>
  );
}
