"use client";

import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Plus, Pencil, Building2 } from "lucide-react";
import ReferrerModal from "@/components/staff/ReferrerModal";

type Referrer = {
  id: string;
  code: string;
  name: string;
  contact_name?: string;
  address?: string;
  postal_code?: string;
  city?: string;
  email?: string;
  created_at: string;
};

export default function ApporteursPage() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingReferrer, setEditingReferrer] = useState<Referrer | null>(null);
  const queryClient = useQueryClient();

  // Récupération de la liste des apporteurs
  const { data: referrers = [], isLoading } = useQuery<Referrer[]>({
    queryKey: ["staff-referrers"],
    queryFn: async () => {
      const res = await fetch("/api/staff/referrers", {
        credentials: "include"
      });
      if (!res.ok) {
        throw new Error("Erreur lors de la récupération des apporteurs");
      }
      return res.json();
    }
  });

  const handleEdit = (referrer: Referrer) => {
    setEditingReferrer(referrer);
    setIsModalOpen(true);
  };

  const handleCreate = () => {
    setEditingReferrer(null);
    setIsModalOpen(true);
  };

  const handleSuccess = () => {
    queryClient.invalidateQueries({ queryKey: ["staff-referrers"] });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-slate-600">Chargement...</div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Apporteurs d'affaires</h1>
          <p className="text-sm text-slate-600 mt-1">
            Gérez les informations des apporteurs d'affaires
          </p>
        </div>
        <button
          onClick={handleCreate}
          className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition"
        >
          <Plus className="w-4 h-4" />
          Nouvel apporteur
        </button>
      </div>

      <div className="bg-white rounded-lg shadow-sm border border-slate-200">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-700 uppercase">
                  Code
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-700 uppercase">
                  Nom
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-700 uppercase">
                  Contact
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-700 uppercase">
                  Adresse
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-700 uppercase">
                  Email
                </th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-slate-700 uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {referrers.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-8 text-center text-slate-500">
                    <Building2 className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                    <p>Aucun apporteur d'affaires enregistré</p>
                  </td>
                </tr>
              ) : (
                referrers.map((referrer) => (
                  <tr key={referrer.id} className="hover:bg-slate-50 transition">
                    <td className="px-4 py-3 text-sm font-semibold text-slate-900">
                      {referrer.code}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-800">
                      {referrer.name}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">
                      {referrer.contact_name || "-"}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">
                      {referrer.address ? (
                        <div>
                          <div>{referrer.address}</div>
                          <div>{referrer.postal_code} {referrer.city}</div>
                        </div>
                      ) : "-"}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">
                      {referrer.email || "-"}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-2">
                        <button
                          onClick={() => handleEdit(referrer)}
                          className="p-1.5 text-slate-600 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition"
                          title="Modifier"
                        >
                          <Pencil className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal */}
      {isModalOpen && (
        <ReferrerModal
          referrer={editingReferrer}
          onClose={() => setIsModalOpen(false)}
          onSuccess={handleSuccess}
        />
      )}
    </div>
  );
}
