"use client";

import { useEffect, useMemo, useState } from "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;
};

type EmailDetailViewProps = {
  mode: "admin" | "user";
  emailId: string;
};

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

export function EmailDetailView({ mode, emailId }: EmailDetailViewProps) {
  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 backHref = mode === "admin" ? "/admin/emails" : "/my-emails";
  const title = mode === "admin" ? "Admin email drilldown" : "Email drilldown";

  const load = 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,
      });
    } catch (fetchError) {
      setError(fetchError instanceof Error ? fetchError.message : "Failed to load email row");
      setData(null);
    } finally {
      setLoading(false);
    }
  };

  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);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [endpoint, emailId]);

  const email = useMemo(
    () => data?.emails.find((row) => row.id === emailId) ?? null,
    [data, emailId],
  );

  return (
    <main className="mx-auto mt-10 w-full max-w-5xl px-4 pb-10">
      <Card>
        <CardHeader className="space-y-3">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <SharedBackButton fallbackHref={backHref} />
            <Badge variant={loading ? "warning" : "secondary"}>
              auto refresh: {loading ? "syncing" : "on (30s + focus)"}
            </Badge>
          </div>
          <div>
            <CardTitle>{title}</CardTitle>
            <CardDescription>Email row id: {emailId}</CardDescription>
          </div>
        </CardHeader>
        <CardContent className="grid gap-4">
          <div className="flex flex-wrap gap-2 text-xs">
            <Badge variant={loading ? "secondary" : error ? "destructive" : email ? "success" : "warning"}>
              {loading ? "loading" : error ? "error" : email ? "found" : "not found"}
            </Badge>
            <Badge variant="secondary">scope 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}
          {!loading && !error && !email ? (
            <p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
              Email row not found in this scope. It may be outside the current permissions or older than the loaded window.
            </p>
          ) : null}

          {email ? (
            <>
              <section className="grid gap-3 rounded-xl border border-slate-200 bg-white p-4 text-sm">
                <div>
                  <span className="font-semibold text-slate-700">Created:</span> {email.createdAt}
                </div>
                <div>
                  <span className="font-semibold text-slate-700">Recipient:</span> {email.recipientEmail}
                </div>
                <div>
                  <span className="font-semibold text-slate-700">Subject:</span> {email.subject}
                </div>
                <div>
                  <span className="font-semibold text-slate-700">Provider:</span> {email.provider}
                </div>
                <div>
                  <span className="font-semibold text-slate-700">From:</span>{" "}
                  {email.fromName ? `${email.fromName} <${email.fromAddress}>` : email.fromAddress}
                </div>
              </section>
              <section className="grid gap-2">
                <h3 className="text-sm font-semibold text-slate-900">Metadata</h3>
                <pre className="max-h-[380px] overflow-auto rounded-xl border border-slate-200 bg-slate-950 p-4 text-xs text-slate-100">
                  {email.metadata ? safeStringify(email.metadata) : "null"}
                </pre>
              </section>
            </>
          ) : null}
        </CardContent>
      </Card>
    </main>
  );
}
