"use client";

import { useState } from "react";
import { ClientCard } from "./ClientCard";
import { ClientModal } from "./ClientModal";
import type { ClientContact } from "@/lib/db/schema";

type ClientRow = {
  id: string;
  name: string;
  email: string;
  contacts?: ClientContact[] | null;
  docCount: number;
  lastActivity: Date | null;
  createdAt: Date;
};

export function ClientsPageClient({ clients }: { clients: ClientRow[] }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "1.5rem" }}>
        <div>
          <h1 style={{ color: "#1B2B4B", fontSize: "1.5rem", fontWeight: 700, marginBottom: "0.25rem" }}>Clients</h1>
          <p style={{ color: "#6B7280", fontSize: "0.875rem" }}>{clients.length} client{clients.length !== 1 ? "s" : ""}</p>
        </div>
        <button
          onClick={() => setIsOpen(true)}
          className="rounded-lg px-4 py-2 text-sm font-semibold text-white transition hover:brightness-110"
          style={{ backgroundColor: "#C9A84C" }}
        >
          + Add Client
        </button>
      </div>

      {clients.length === 0 ? (
        <div style={{ textAlign: "center", padding: "4rem 0" }}>
          <p style={{ color: "#6B7280", marginBottom: "1rem" }}>No clients yet.</p>
          <button
            onClick={() => setIsOpen(true)}
            className="rounded-lg px-4 py-2 text-sm font-semibold text-white transition hover:brightness-110"
            style={{ backgroundColor: "#C9A84C" }}
          >
            + Add your first client
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {clients.map((client) => (
            <ClientCard
              key={client.id}
              id={client.id}
              name={client.name}
              email={client.email}
              contacts={client.contacts ?? []}
              docCount={client.docCount}
              lastActivity={client.lastActivity}
            />
          ))}
        </div>
      )}

      <ClientModal isOpen={isOpen} onClose={() => setIsOpen(false)} mode="create" />
    </div>
  );
}
