import Link from "next/link";
import { notFound } from "next/navigation";
import { eq, asc } from "drizzle-orm";
import { ArrowLeft } from "@/components/ui/icons";
import { Topbar } from "@/components/shell/topbar";
import { Panel, PanelHeader } from "@/components/ui/panel";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import { db } from "@/lib/db";
import { clientAccount, clientSite, user } from "@/lib/db/schema";
import { getServiceAccountEmail } from "@/lib/google";
import { formatDate } from "@/lib/format";
import { SitesManager } from "./sites-manager";

const PLAN_LABELS: Record<string, string> = {
  presence: "Presence",
  developpement: "Developpement",
  ecommerce: "E-commerce",
};

const STATUS_TONES: Record<string, "success" | "warning" | "danger" | "muted"> = {
  actif: "success",
  suspendu: "warning",
  annule: "danger",
};

const STATUS_LABELS: Record<string, string> = {
  actif: "Actif",
  suspendu: "Suspendu",
  annule: "Annule",
};

type PageProps = { params: Promise<{ id: string }> };

export default async function ClientDetailPage({ params }: PageProps) {
  const { id } = await params;

  const accountRows = await db
    .select()
    .from(clientAccount)
    .where(eq(clientAccount.id, id))
    .limit(1);

  if (accountRows.length === 0) notFound();
  const account = accountRows[0];

  const [sites, contacts] = await Promise.all([
    db
      .select()
      .from(clientSite)
      .where(eq(clientSite.clientAccountId, id))
      .orderBy(asc(clientSite.createdAt)),
    db
      .select({ id: user.id, name: user.name, email: user.email, createdAt: user.createdAt })
      .from(user)
      .where(eq(user.clientAccountId, id)),
  ]);

  const serviceAccountEmail = getServiceAccountEmail();

  return (
    <>
      <Topbar
        title={account.companyName}
        subtitle={`Compte cree le ${formatDate(account.createdAt.toISOString())}`}
        trailing={
          <div className="flex items-center gap-2">
            <Badge tone={STATUS_TONES[account.status] ?? "muted"} dot>
              {STATUS_LABELS[account.status] ?? account.status}
            </Badge>
            <Link href="/atelier-novelia/clients">
              <Button variant="ghost" size="sm">
                <ArrowLeft className="size-3.5" />
                Retour
              </Button>
            </Link>
          </div>
        }
      />

      <div className="pt-6 space-y-6">
        {/* Infos du compte */}
        <Panel>
          <PanelHeader
            title="Informations du compte"
            subtitle="Contact principal et formule"
          />
          <div className="px-6 py-5 grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
            <div>
              <div className="text-xxs uppercase tracking-wider text-text-faint">Raison sociale</div>
              <div className="mt-1 text-text">{account.companyName}</div>
            </div>
            <div>
              <div className="text-xxs uppercase tracking-wider text-text-faint">Contact</div>
              <div className="mt-1 text-text">{account.contactName}</div>
              <div className="text-xs text-text-dim">{account.contactEmail}</div>
            </div>
            <div>
              <div className="text-xxs uppercase tracking-wider text-text-faint">Plan</div>
              <div className="mt-1 text-text">{PLAN_LABELS[account.plan] ?? account.plan}</div>
            </div>
            {account.notes ? (
              <div className="md:col-span-3 border-t border-border pt-4 mt-2">
                <div className="text-xxs uppercase tracking-wider text-text-faint">Notes internes</div>
                <p className="mt-1 text-sm text-text-muted whitespace-pre-line">{account.notes}</p>
              </div>
            ) : null}
          </div>
        </Panel>

        {/* Sites */}
        <SitesManager
          clientAccountId={account.id}
          sites={sites.map((s) => ({
            id: s.id,
            domain: s.domain,
            label: s.label,
            status: s.status,
            plan: s.plan,
            monthlyAmountCents: s.monthlyAmountCents,
            searchConsoleSiteUrl: s.searchConsoleSiteUrl,
            ga4PropertyId: s.ga4PropertyId,
          }))}
          serviceAccountEmail={serviceAccountEmail}
        />

        {/* Utilisateurs du portail rattaches au compte */}
        <Panel>
          <PanelHeader
            title="Acces portail"
            subtitle="Utilisateurs ayant un acces /portail rattache a ce compte"
          />
          {contacts.length === 0 ? (
            <div className="px-6 py-8 text-sm text-text-dim text-center">
              Aucun utilisateur rattache. Le compte a ete cree sans acces portail.
            </div>
          ) : (
            <ul className="divide-y divide-border">
              {contacts.map((c) => (
                <li key={c.id} className="px-6 py-3.5 flex items-center gap-3">
                  <Avatar initials={c.name.slice(0, 2)} variant="client" size="sm" />
                  <div className="min-w-0 flex-1">
                    <div className="text-sm text-text truncate">{c.name}</div>
                    <div className="text-xs text-text-dim truncate">{c.email}</div>
                  </div>
                  <form action="/api/admin/impersonate" method="POST" className="shrink-0">
                    <input type="hidden" name="userId" value={c.id} />
                    <Button type="submit" variant="ghost" size="sm">
                      Voir le portail
                    </Button>
                  </form>
                  <div className="text-xs text-text-faint shrink-0">
                    Cree le {formatDate(c.createdAt.toISOString())}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </Panel>
      </div>
    </>
  );
}
