"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { fetchTerm } from "./client-api";
import { MarkdownPreview } from "./content-fields";
import type { TermsRecord } from "./types";

export function TermsPreviewDialog({ item, open, onClose }: {
  item: TermsRecord;
  open: boolean;
  onClose: () => void;
}) {
  const [current, setCurrent] = useState<TermsRecord>(item);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const viewingPrevious = !!item && current?.id !== item.id;

  async function showPrevious() {
    if (!item?.previousVersionId) return;
    setLoading(true);
    setError("");
    try {
      setCurrent(await fetchTerm(item.previousVersionId));
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Unable to load the previous version.");
    } finally {
      setLoading(false);
    }
  }

  const effectiveDate = current.effectiveFrom
    ? new Date(current.effectiveFrom).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" })
    : "No date set";

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl">
        <DialogHeader>
          <div className="flex flex-wrap items-start justify-between gap-3 pr-8">
            <div>
              <DialogTitle>{current.title}</DialogTitle>
              <DialogDescription className="mt-1">
                {viewingPrevious ? "Previous version" : "Terms & Conditions preview"}
              </DialogDescription>
            </div>
            <span className={`rounded-full px-3 py-1 text-xs font-medium ${current.status === "published" ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-400" : "bg-amber-500/10 text-amber-800 dark:text-amber-300"}`}>
              {current.status}
            </span>
          </div>
        </DialogHeader>
        <dl className="grid gap-4 rounded-xl border bg-muted/30 p-4 sm:grid-cols-2">
          {current.versionLabel && <div><dt className="text-xs font-medium uppercase text-muted-foreground">Version</dt><dd className="mt-1 text-sm">{current.versionLabel}</dd></div>}
          <div><dt className="text-xs font-medium uppercase text-muted-foreground">Effective date</dt><dd className="mt-1 text-sm">{effectiveDate}</dd></div>
          {current.jurisdiction && <div><dt className="text-xs font-medium uppercase text-muted-foreground">Jurisdiction</dt><dd className="mt-1 text-sm">{current.jurisdiction}</dd></div>}
          {current.locale && <div><dt className="text-xs font-medium uppercase text-muted-foreground">Locale</dt><dd className="mt-1 text-sm">{current.locale}</dd></div>}
        </dl>
        <div className="rounded-xl border bg-card p-5 sm:p-7">
          <MarkdownPreview value={current.body} />
        </div>
        {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
        <DialogFooter>
          {viewingPrevious ? (
            <Button type="button" variant="outline" onClick={() => setCurrent(item)}>Back to current version</Button>
          ) : item?.previousVersionId ? (
            <Button type="button" variant="outline" disabled={loading} onClick={() => void showPrevious()}>{loading ? "Loading…" : "View previous version"}</Button>
          ) : null}
          <Button type="button" onClick={onClose}>Close</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
