"use client";

import { useState } from "react";
import { Mail, MessageSquare, RefreshCw, Save, Send } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, CardHeader, DataTable, Field, Input, Modal, PageHeader, Pagination, Select, Tabs, Textarea, useToast, type Column } from "@/components/ui";
import { formatDateTime, qs } from "@/lib/utils";

interface LogRow extends Record<string, unknown> {
  id: number;
  phone?: string;
  email?: string;
  message?: string;
  subject?: string;
  templateKey: string | null;
  status: string;
  providerRef?: string | null;
  error?: string | null;
  createdAt: string;
}
interface Template {
  id: number;
  channel: string;
  key: string;
  name: string;
  subject: string | null;
  body: string;
  isActive: boolean;
}

export default function MessagesPage() {
  const toast = useToast();
  const [tab, setTab] = useState<"sms" | "email" | "templates">("sms");
  const [page, setPage] = useState(1);
  const { data: logs, loading, reload } = useApi<{ items: LogRow[]; total: number; page: number; pageSize: number }>(`/api/logs${qs({ type: tab, page, pageSize: 20 })}`, [tab, page]);
  const { data: templates, reload: reloadTemplates } = useApi<{ items: Template[] }>("/api/templates");
  const [editing, setEditing] = useState<Template | null>(null);
  const [body, setBody] = useState("");
  const [subject, setSubject] = useState("");
  const [busy, setBusy] = useState(false);

  const columns: Column<LogRow>[] =
    tab === "sms"
      ? [
          { key: "createdAt", label: "When", render: (r) => <span className="font-mono text-[11px] text-slate-400">{formatDateTime(r.createdAt)}</span> },
          { key: "phone", label: "Phone", render: (r) => <span className="font-mono text-xs">{String(r.phone ?? "—")}</span> },
          { key: "templateKey", label: "Template", hideOnMobile: true, render: (r) => <Badge value="unknown" label={String(r.templateKey ?? "ad-hoc")} /> },
          { key: "message", label: "Message", render: (r) => <span className="line-clamp-2 max-w-md text-slate-300">{String(r.message ?? "")}</span> },
          { key: "status", label: "Status", render: (r) => <Badge value={r.status} /> },
          { key: "error", label: "Error", hideOnMobile: true, render: (r) => String(r.error ?? "—") },
        ]
      : [
          { key: "createdAt", label: "When", render: (r) => <span className="font-mono text-[11px] text-slate-400">{formatDateTime(r.createdAt)}</span> },
          { key: "email", label: "To" },
          { key: "subject", label: "Subject", render: (r) => String(r.subject ?? "—") },
          { key: "templateKey", label: "Template", hideOnMobile: true, render: (r) => <Badge value="unknown" label={String(r.templateKey ?? "ad-hoc")} /> },
          { key: "status", label: "Status", render: (r) => <Badge value={r.status} /> },
          { key: "error", label: "Error", hideOnMobile: true, render: (r) => String(r.error ?? "—") },
        ];

  return (
    <>
      <PageHeader
        title="SMS & email centre"
        subtitle="Gateway outbox, delivery status and editable templates"
        icon={<MessageSquare className="h-5 w-5" />}
        actions={
          <Button variant="secondary" size="sm" icon={<RefreshCw className="h-4 w-4" />} onClick={() => void reload()}>
            Refresh
          </Button>
        }
      />

      <div className="mb-4">
        <Tabs
          value={tab}
          onChange={setTab}
          tabs={[
            { value: "sms", label: "SMS outbox", icon: <MessageSquare className="h-3.5 w-3.5" /> },
            { value: "email", label: "Email outbox", icon: <Mail className="h-3.5 w-3.5" /> },
            { value: "templates", label: "Templates", icon: <Save className="h-3.5 w-3.5" /> },
          ]}
        />
      </div>

      {tab === "templates" ? (
        <div className="grid gap-4 md:grid-cols-2">
          {(templates?.items ?? []).map((t) => (
            <Card key={t.id}>
              <CardHeader title={t.name} subtitle={`${t.channel.toUpperCase()} · {{${t.key}}}`} action={<Badge value={t.isActive ? "active" : "inactive"} />} />
              <div className="space-y-2 p-4">
                {t.subject ? <p className="text-xs text-slate-400">Subject: {t.subject}</p> : null}
                <p className="whitespace-pre-wrap rounded-xl border border-white/8 bg-white/4 p-3 text-xs text-slate-300">{t.body}</p>
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => {
                    setEditing(t);
                    setBody(t.body);
                    setSubject(t.subject ?? "");
                  }}
                >
                  Edit template
                </Button>
              </div>
            </Card>
          ))}
        </div>
      ) : (
        <Card className="p-2">
          <DataTable columns={columns} rows={logs?.items ?? []} loading={loading} rowKey={(r) => r.id} empty="No messages sent yet" />
          <Pagination page={logs?.page ?? 1} pages={Math.max(1, Math.ceil((logs?.total ?? 0) / (logs?.pageSize ?? 20)))} total={logs?.total ?? 0} onChange={setPage} />
        </Card>
      )}

      <Modal
        open={Boolean(editing)}
        onClose={() => setEditing(null)}
        title={`Edit template — ${editing?.name ?? ""}`}
        subtitle="Available placeholders: {{customer_name}}, {{invoice_no}}, {{amount}}, {{due_date}}, {{isp_name}}…"
        footer={
          <>
            <Button variant="secondary" onClick={() => setEditing(null)}>
              Cancel
            </Button>
            <Button
              loading={busy}
              onClick={async () => {
                if (!editing) return;
                setBusy(true);
                try {
                  await api("/api/templates", { method: "PUT", json: { id: editing.id, body, subject: subject || null } });
                  toast.push("Template saved", "success");
                  setEditing(null);
                  void reloadTemplates();
                } catch (err) {
                  toast.push(err instanceof Error ? err.message : "Save failed", "error");
                } finally {
                  setBusy(false);
                }
              }}
            >
              Save template
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Field label="Subject (email only)">
            <Input value={subject} onChange={(e) => setSubject(e.target.value)} />
          </Field>
          <Field label="Body">
            <Textarea value={body} onChange={(e) => setBody(e.target.value)} className="min-h-40" />
          </Field>
          <Select
            value={editing?.isActive ? "on" : "off"}
            onChange={async (e) => {
              if (!editing) return;
              await api("/api/templates", { method: "PUT", json: { id: editing.id, body: editing.body, isActive: e.target.value === "on" } });
              setEditing({ ...editing, isActive: e.target.value === "on" });
              void reloadTemplates();
            }}
          >
            <option value="on">Active</option>
            <option value="off">Disabled</option>
          </Select>
        </div>
      </Modal>
    </>
  );
}
