"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import AdminLayout from "@/components/admin/AdminLayout";
import ClientForm from "@/components/admin/ClientForm";
import ClientList from "@/components/admin/ClientList";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
import { Client } from "@/lib/types/client";

export default function AdminPage() {
  const [showForm, setShowForm] = useState(false);
  const [editingClient, setEditingClient] = useState<Client | undefined>();
  const [refreshKey, setRefreshKey] = useState(0);
  const router = useRouter();

  useEffect(() => {
    // Vérifier si l'admin est connecté
    const adminPassword = localStorage.getItem("adminPassword");
    if (!adminPassword) {
      router.push("/admin/login");
    }
  }, [router]);

  const handleNewClient = () => {
    setEditingClient(undefined);
    setShowForm(true);
  };

  const handleEdit = (client: Client) => {
    setEditingClient(client);
    setShowForm(true);
  };

  const handleSuccess = () => {
    setShowForm(false);
    setEditingClient(undefined);
    setRefreshKey((k) => k + 1);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingClient(undefined);
  };

  return (
    <AdminLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold text-primary">Gestion des clients</h2>
          {!showForm && (
            <Button onClick={handleNewClient}>
              <Plus className="h-4 w-4 mr-2" />
              Nouveau client
            </Button>
          )}
        </div>

        {showForm ? (
          <ClientForm
            client={editingClient}
            onSuccess={handleSuccess}
            onCancel={handleCancel}
          />
        ) : (
          <ClientList onEdit={handleEdit} onRefresh={() => setRefreshKey((k) => k + 1)} />
        )}
      </div>
    </AdminLayout>
  );
}

