"use client";

import { useMemo, useState } from "react";
import {
  CalendarDays,
  Mail,
  Phone,
  Search,
  Users,
  UserCheck,
  UserX,
  X,
} from "lucide-react";

type Client = {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string | null;
  isActive: boolean;
  createdAt: Date | string;
};

type ClientsTableProps = {
  clients: Client[];
};

export default function ClientsTable({
  clients,
}: ClientsTableProps) {
  const [search, setSearch] = useState("");

  // ================================
  // STATISTIQUES
  // ================================

  const totalClients = clients.length;

  const activeClients = clients.filter(
    (client) => client.isActive
  ).length;

  const inactiveClients = clients.filter(
    (client) => !client.isActive
  ).length;

  // ================================
  // RECHERCHE
  // ================================

  const filteredClients = useMemo(() => {
    const searchValue = search.trim().toLowerCase();

    if (!searchValue) {
      return clients;
    }

    return clients.filter((client) => {
      const fullName =
        `${client.firstName} ${client.lastName}`.toLowerCase();

      const reverseName =
        `${client.lastName} ${client.firstName}`.toLowerCase();

      const email = client.email.toLowerCase();

      const phone =
        client.phone?.toLowerCase() || "";

      return (
        fullName.includes(searchValue) ||
        reverseName.includes(searchValue) ||
        email.includes(searchValue) ||
        phone.includes(searchValue)
      );
    });
  }, [clients, search]);

  // ================================
  // FORMATAGE DATE
  // ================================

  function formatDate(date: Date | string) {
    try {
      return new Intl.DateTimeFormat("fr-FR", {
        dateStyle: "medium",
      }).format(new Date(date));
    } catch {
      return "Date inconnue";
    }
  }

  return (
    <div className="mx-auto max-w-7xl space-y-8">

      {/* ================================
          HEADER
      ================================= */}

      <div>
        <p className="text-sm font-semibold uppercase tracking-[0.25em] text-[#a68b5b]">
          Gestion
        </p>

        <h1 className="mt-2 text-3xl font-bold tracking-tight text-[#2f2a24]">
          Gestion des clients
        </h1>

        <p className="mt-2 text-sm text-gray-500">
          Consultez et recherchez les clients
          enregistrés sur la plateforme.
        </p>
      </div>

      {/* ================================
          STATISTIQUES
      ================================= */}

      <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">

        {/* TOTAL CLIENTS */}

        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between">

            <p className="text-sm text-gray-500">
              Total clients
            </p>

            <Users
              size={21}
              className="text-[#a68b5b]"
            />

          </div>

          <p className="mt-3 text-3xl font-bold text-[#2f2a24]">
            {totalClients}
          </p>

          <p className="mt-2 text-xs text-[#a68b5b]">
            Clients enregistrés
          </p>
        </div>

        {/* CLIENTS ACTIFS */}

        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between">

            <p className="text-sm text-gray-500">
              Clients actifs
            </p>

            <UserCheck
              size={21}
              className="text-green-500"
            />

          </div>

          <p className="mt-3 text-3xl font-bold text-green-600">
            {activeClients}
          </p>

          <p className="mt-2 text-xs text-gray-400">
            Comptes actifs
          </p>
        </div>

        {/* CLIENTS DÉSACTIVÉS */}

        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between">

            <p className="text-sm text-gray-500">
              Clients désactivés
            </p>

            <UserX
              size={21}
              className="text-red-500"
            />

          </div>

          <p className="mt-3 text-3xl font-bold text-red-600">
            {inactiveClients}
          </p>

          <p className="mt-2 text-xs text-gray-400">
            Comptes désactivés
          </p>
        </div>

      </div>

      {/* ================================
          LISTE DES CLIENTS
      ================================= */}

      <div className="rounded-2xl border border-[#e8e1d6] bg-white shadow-sm">

        {/* HEADER DE LA LISTE */}

        <div className="border-b border-[#eee8df] p-6">

          <div className="flex flex-col justify-between gap-5 lg:flex-row lg:items-center">

            <div>
              <h2 className="text-lg font-semibold text-[#2f2a24]">
                Liste des clients
              </h2>

              <p className="mt-1 text-sm text-gray-500">
                {filteredClients.length} client
                {filteredClients.length > 1 ? "s" : ""}{" "}
                trouvé
                {filteredClients.length > 1 ? "s" : ""}
              </p>
            </div>

            {/* RECHERCHE */}

            <div className="relative w-full lg:max-w-md">

              <Search
                size={18}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
              />

              <input
                type="search"
                value={search}
                onChange={(event) =>
                  setSearch(event.target.value)
                }
                placeholder="Rechercher par nom, e-mail ou téléphone..."
                className="w-full rounded-xl border border-[#e8e1d6] bg-white py-3 pl-11 pr-11 text-sm outline-none transition focus:border-[#a68b5b] focus:ring-2 focus:ring-[#a68b5b]/10"
              />

              {/* EFFACER LA RECHERCHE */}

              {search && (
                <button
                  type="button"
                  onClick={() => setSearch("")}
                  aria-label="Effacer la recherche"
                  className="absolute right-3 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full text-gray-400 transition hover:bg-[#f8f6f1] hover:text-[#2f2a24]"
                >
                  <X size={16} />
                </button>
              )}

            </div>

          </div>

        </div>

        {/* ================================
            AUCUN CLIENT
        ================================= */}

        {filteredClients.length === 0 && (
          <div className="p-16 text-center">

            <Search
              size={45}
              className="mx-auto text-gray-300"
            />

            <h3 className="mt-5 text-xl font-bold text-[#2f2a24]">
              Aucun client trouvé
            </h3>

            <p className="mt-2 text-sm text-gray-500">
              {search
                ? "Aucun client ne correspond à votre recherche."
                : "Aucun client n'est encore enregistré."}
            </p>

            {search && (
              <button
                type="button"
                onClick={() => setSearch("")}
                className="mt-5 rounded-xl bg-[#2f2a24] px-5 py-3 text-sm font-semibold text-white transition hover:bg-[#4a4238]"
              >
                Réinitialiser la recherche
              </button>
            )}

          </div>
        )}

        {/* ================================
            TABLEAU
        ================================= */}

        {filteredClients.length > 0 && (
          <div className="overflow-x-auto">

            <table className="w-full min-w-[850px]">

              <thead>
                <tr className="border-b border-[#eee8df] bg-[#f8f6f1] text-left">

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Client
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Contact
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Inscription
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Statut
                  </th>

                </tr>
              </thead>

              <tbody>

                {filteredClients.map((client) => {

                  const initials =
                    `${client.firstName.charAt(0)}${client.lastName.charAt(0)}`
                      .toUpperCase();

                  return (
                    <tr
                      key={client.id}
                      className="border-b border-[#eee8df] last:border-b-0 hover:bg-[#fcfbf8]"
                    >

                      {/* CLIENT */}

                      <td className="px-6 py-5">

                        <div className="flex items-center gap-4">

                          <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#d8c19a] font-semibold text-white">
                            {initials}
                          </div>

                          <div className="min-w-0">

                            <p className="font-semibold text-[#2f2a24]">
                              {client.firstName}{" "}
                              {client.lastName}
                            </p>

                            <p className="mt-1 text-xs text-gray-400">
                              Client
                            </p>

                          </div>

                        </div>

                      </td>

                      {/* CONTACT */}

                      <td className="px-6 py-5">

                        <div className="space-y-2">

                          <div className="flex items-center gap-2 text-sm text-gray-600">

                            <Mail
                              size={15}
                              className="shrink-0 text-[#a68b5b]"
                            />

                            <span>
                              {client.email}
                            </span>

                          </div>

                          {client.phone && (
                            <div className="flex items-center gap-2 text-sm text-gray-600">

                              <Phone
                                size={15}
                                className="shrink-0 text-[#a68b5b]"
                              />

                              <span>
                                {client.phone}
                              </span>

                            </div>
                          )}

                        </div>

                      </td>

                      {/* DATE D'INSCRIPTION */}

                      <td className="px-6 py-5">

                        <div className="flex items-center gap-2 text-sm text-gray-600">

                          <CalendarDays
                            size={16}
                            className="shrink-0 text-[#a68b5b]"
                          />

                          <span>
                            {formatDate(
                              client.createdAt
                            )}
                          </span>

                        </div>

                      </td>

                      {/* STATUT */}

                      <td className="px-6 py-5">

                        <span
                          className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${
                            client.isActive
                              ? "bg-green-100 text-green-700"
                              : "bg-red-100 text-red-700"
                          }`}
                        >
                          {client.isActive
                            ? "Actif"
                            : "Désactivé"}
                        </span>

                      </td>

                    </tr>
                  );
                })}

              </tbody>

            </table>

          </div>
        )}

      </div>

    </div>
  );
}