"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import NextLink from "next/link";
import { Table } from "@heroui/react";
import { SharedBackButton } from "./shared-back-button";
import { Badge } from "./ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card";

type EmailRow = {
  id: string;
  recipientEmail: string;
  subject: string;
  fromAddress: string;
  fromName?: string | null;
  provider: string;
  createdAt: string;
  metadata?: unknown;
};

type EmailResponse = {
  emails: EmailRow[];
  total: number;
  limit: number;
  offset: number;
};

const columns = [
  { key: "createdAt", label: "Created" },
  { key: "recipientEmail", label: "Recipient" },
  { key: "subject", label: "Subject" },
  { key: "provider", label: "Provider" },
  { key: "from", label: "From" },
  { key: "metadata", label: "Metadata" },
  { key: "details", label: "Details" },
];

function safeStringify(value: unknown): string {
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
}

export function EmailHistoryTable({ mode }: { mode: "admin" | "user" }) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<EmailResponse | null>(null);

  const endpoint = mode === "admin" ? "/api/auth/admin/email/list?limit=250&offset=0" : "/api/auth/email/list?limit=250&offset=0";
  const title = mode === "admin" ? "Admin email history" : "Your email history";
  const description =
    mode === "admin"
      ? "All rows from the sent `emails` table."
      : "Only rows where recipient email matches your authenticated account.";

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(endpoint, {
        method: "GET",
        credentials: "include",
        cache: "no-store",
      });
      const body = (await response.json().catch(() => ({}))) as Record<string, unknown>;
      if (!response.ok) {
        const message =
          typeof body.message === "string"
            ? body.message
            : typeof body.error === "string"
              ? body.error
              : `${response.status} ${response.statusText}`;
        throw new Error(message);
      }
      setData({
        emails: Array.isArray(body.emails) ? (body.emails as EmailRow[]) : [],
        total: typeof body.total === "number" ? body.total : 0,
        limit: typeof body.limit === "number" ? body.limit : 0,
        offset: typeof body.offset === "number" ? body.offset : 0,
      });
    } catch (fetchError) {
      setError(fetchError instanceof Error ? fetchError.message : "Failed to load email history");
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [endpoint]);

  useEffect(() => {
    void load();
    const onVisible = () => {
      if (!document.hidden) {
        void load();
      }
    };
    const interval = window.setInterval(() => {
      void load();
    }, 30000);
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      window.clearInterval(interval);
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, [load]);

  const rows = useMemo(() => {
    if (data?.emails?.length) return data.emails;
    return [];
  }, [data]);

  return (
    <main className="mx-auto mt-10 w-full max-w-7xl px-4 pb-10">
      <Card>
        <CardHeader className="space-y-3">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <SharedBackButton fallbackHref="/login" />
            <Badge variant={loading ? "warning" : "secondary"}>
              auto refresh: {loading ? "syncing" : "on (30s + focus)"}
            </Badge>
          </div>
          <div>
            <CardTitle>{title}</CardTitle>
            <CardDescription>{description}</CardDescription>
          </div>
        </CardHeader>
        <CardContent className="grid gap-4">
          <div className="flex flex-wrap gap-2 text-xs">
            <Badge variant={loading ? "secondary" : error ? "destructive" : "success"}>
              {loading ? "loading" : error ? "error" : "loaded"}
            </Badge>
            <Badge variant="secondary">rows: {data?.total ?? 0}</Badge>
            <Badge variant="secondary">endpoint: {endpoint}</Badge>
          </div>

          {error ? <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{error}</p> : null}

          <Table>
            <Table.Content aria-label={`${mode} sent email history`}>
              <Table.Header>
                {columns.map((column, index) => (
                  <Table.Column key={column.key} id={column.key} isRowHeader={index === 0}>
                    {column.label}
                  </Table.Column>
                ))}
              </Table.Header>
              <Table.Body
                items={
                  rows.length
                    ? rows
                    : [
                        {
                          id: "empty",
                          recipientEmail: "-",
                          subject: "No sent emails found",
                          fromAddress: "-",
                          fromName: null,
                          provider: "-",
                          createdAt: "-",
                          metadata: null,
                        },
                      ]
                }
              >
                {(item) => (
                  <Table.Row key={item.id} id={item.id}>
                    <Table.Cell>{item.createdAt}</Table.Cell>
                    <Table.Cell>{item.recipientEmail}</Table.Cell>
                    <Table.Cell>{item.subject}</Table.Cell>
                    <Table.Cell>{item.provider}</Table.Cell>
                    <Table.Cell>{item.fromName ? `${item.fromName} <${item.fromAddress}>` : item.fromAddress}</Table.Cell>
                    <Table.Cell className="max-w-[340px] truncate">{item.metadata ? safeStringify(item.metadata) : "-"}</Table.Cell>
                    <Table.Cell>
                      {item.id !== "empty" ? (
                        <NextLink
                          href={mode === "admin" ? `/admin/emails/${item.id}` : `/my-emails/${item.id}`}
                          className="text-sm font-medium text-violet-700 hover:text-violet-900"
                        >
                          Open
                        </NextLink>
                      ) : (
                        "-"
                      )}
                    </Table.Cell>
                  </Table.Row>
                )}
              </Table.Body>
            </Table.Content>
          </Table>
        </CardContent>
      </Card>
    </main>
  );
}
