"use client";

import { useCallback, useEffect, useState } from "react";
import { Megaphone, Send, Mail } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Input, Select, FormField, Badge } from "@/components/ui";
import { DataTable, type Column } from "@/components/data-table";
import { useToast } from "@/components/toast";

type Email = { id: string; to: string; type: string; subject: string; date: string; status: string };

const TYPE_TONE: Record<string, "brand" | "success" | "info" | "warning" | "neutral"> = {
  welcome: "success",
  sale_notification: "info",
  payout: "brand",
  bulk_broadcast: "warning",
};

export default function MarketingPage() {
  const toast = useToast();
  const [logs, setLogs] = useState<Email[]>([]);
  const [loading, setLoading] = useState(true);
  const [subject, setSubject] = useState("");
  const [audience, setAudience] = useState("all");
  const [sending, setSending] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setLogs(await api.get("/admin/emails"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const send = async () => {
    if (!subject.trim()) {
      toast.error("Enter a subject first.");
      return;
    }
    setSending(true);
    try {
      const r = await api.post("/admin/emails/bulk", { subject, audience });
      toast.success(`Broadcast sent to ${r.sent} affiliate(s).`);
      setSubject("");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSending(false);
    }
  };

  const columns: Column<Email>[] = [
    { key: "to", header: "Recipient", sortable: true, accessor: (r) => r.to, render: (r) => <span className="text-gray-700">{r.to}</span> },
    { key: "type", header: "Type", sortable: true, accessor: (r) => r.type, render: (r) => <Badge tone={TYPE_TONE[r.type] ?? "neutral"}>{r.type.replace(/_/g, " ")}</Badge> },
    { key: "subject", header: "Subject", accessor: (r) => r.subject, render: (r) => <span className="text-gray-600">{r.subject}</span> },
    { key: "date", header: "Sent", sortable: true, accessor: (r) => r.date },
    { key: "status", header: "Status", align: "right", accessor: (r) => r.status, render: (r) => <Badge tone="success">{r.status}</Badge> },
  ];

  return (
    <div>
      <PageHeader title="Marketing" subtitle="Emails & broadcasts to affiliates" />

      <div className="mb-4">
        <Card title="Send a broadcast" subtitle="Compose an email to your affiliates">
          <div className="grid gap-4 sm:grid-cols-[1fr_auto_auto] sm:items-end">
            <FormField label="Subject">
              <Input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Big sale this weekend — promote now!" />
            </FormField>
            <FormField label="Audience">
              <Select value={audience} onChange={(e) => setAudience(e.target.value)} className="sm:w-40">
                <option value="all">All affiliates</option>
                <option value="ACTIVE">Active only</option>
                <option value="PENDING">Pending only</option>
              </Select>
            </FormField>
            <Button icon={<Send className="h-4 w-4" />} loading={sending} onClick={send}>
              Send
            </Button>
          </div>
        </Card>
      </div>

      <h3 className="mb-2 text-sm font-semibold text-gray-700">Communications log</h3>
      <DataTable
        columns={columns}
        rows={logs}
        rowKey={(r) => r.id}
        loading={loading}
        exportName="email-log"
        searchPlaceholder="Search recipient, subject…"
        empty={{ icon: <Mail className="h-6 w-6" />, title: "No emails yet", description: "Welcome, sale, payout, and broadcast emails will be logged here." }}
      />
    </div>
  );
}
