import { createClient } from "@/lib/supabase/server";
import { canDo } from "@/lib/auth/permissions";
import { PageHeader } from "@/components/layout/page-header";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { ClientMailClient } from "./client-mail-client";
import type {
  ClientMailCategory,
  ClientMailTemplate,
  ClientMailSend,
} from "@/lib/types";

type TemplateRow = ClientMailTemplate & {
  category?: { name: string } | { name: string }[] | null;
};

export default async function ClientMailPage() {
  const supabase = await createClient();

  const [categoriesRes, templatesRes, sendsRes, leadsRes] = await Promise.all([
    supabase
      .from("client_mail_categories")
      .select("*")
      .order("name"),
    supabase
      .from("client_mail_templates")
      .select("*, category:client_mail_categories(name)")
      .order("created_at", { ascending: false }),
    supabase
      .from("client_mail_sends")
      .select("*")
      .order("created_at", { ascending: false })
      .limit(50),
    supabase
      .from("leads")
      .select("id, full_name, email")
      .not("email", "is", null)
      .limit(500),
  ]);

  const categories = (categoriesRes.data as ClientMailCategory[]) ?? [];
  const templates = ((templatesRes.data as TemplateRow[]) ?? []).map((t) => {
    const cat = Array.isArray(t.category) ? t.category[0] : t.category;
    return { ...t, categoryName: cat?.name ?? null };
  });
  const sends = (sendsRes.data as ClientMailSend[]) ?? [];
  const leads =
    (leadsRes.data as { id: string; full_name: string | null; email: string }[]) ??
    [];

  const canManage = await canDo("promotional", "update");
  const mailConfigured = !!process.env.RESEND_API_KEY;

  const statusVariant = (status: string) =>
    status === "sent"
      ? "default"
      : status === "failed"
        ? "destructive"
        : "secondary";

  return (
    <div className="space-y-6">
      <PageHeader title="Client Mail" breadcrumb="Home / Client Mail" />

      {!mailConfigured && (
        <Card className="border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">
          Email delivery is not configured (no <code>RESEND_API_KEY</code>). Sends
          will be recorded as <span className="font-medium">queued</span>.
        </Card>
      )}

      <ClientMailClient
        categories={categories}
        templates={templates}
        leads={leads}
        canManage={canManage}
        mailConfigured={mailConfigured}
      />

      <Card className="p-0">
        <div className="border-b px-4 py-3 text-sm font-medium">Recent Sends</div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Recipient</TableHead>
              <TableHead>Subject</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Date</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sends.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={4}
                  className="py-10 text-center text-muted-foreground"
                >
                  No emails sent yet.
                </TableCell>
              </TableRow>
            ) : (
              sends.map((s) => (
                <TableRow key={s.id}>
                  <TableCell>
                    <div className="font-medium">{s.recipient_name ?? "—"}</div>
                    <div className="text-xs text-muted-foreground">
                      {s.recipient_email}
                    </div>
                  </TableCell>
                  <TableCell>{s.subject}</TableCell>
                  <TableCell>
                    <Badge variant={statusVariant(s.status)}>{s.status}</Badge>
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {new Date(s.created_at).toLocaleString()}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
