"use client";

import { useState } from "react";
import { FormField } from "@/components/shared/form-field";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import type { TermsWriteValues } from "./content-contract";
import { ChannelPicker, MarkdownInput } from "./content-fields";
import type { ContentChannel, TermsRecord } from "./types";

export function TermsEditorDialog({
  item,
  documents,
  channels,
  open,
  busy,
  onClose,
  onSave,
}: {
  item: TermsRecord | null;
  documents: TermsRecord[];
  channels: ContentChannel[];
  open: boolean;
  busy: boolean;
  onClose: () => void;
  onSave: (values: TermsWriteValues) => Promise<void>;
}) {
  const [title, setTitle] = useState(item?.title ?? "");
  const [body, setBody] = useState(item?.body ?? "");
  const [status, setStatus] = useState<"draft" | "published">(item?.status ?? "draft");
  const [versionLabel, setVersionLabel] = useState(item?.versionLabel ?? "");
  const [effectiveFrom, setEffectiveFrom] = useState(item?.effectiveFrom.slice(0, 10) ?? "");
  const [jurisdiction, setJurisdiction] = useState(item?.jurisdiction ?? "");
  const [locale, setLocale] = useState(item?.locale ?? "");
  const [channelIds, setChannelIds] = useState<string[]>(item?.channelIds ?? []);
  const [previousVersionId, setPreviousVersionId] = useState(item?.previousVersionId ?? "");
  const [error, setError] = useState("");

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    try {
      await onSave({
        title,
        body,
        status,
        versionLabel,
        effectiveFrom,
        jurisdiction,
        locale,
        channelIds,
        previousVersionId,
      });
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Unable to save this Terms document.");
    }
  }

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && !busy && onClose()}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl">
        <DialogHeader>
          <DialogTitle>{item ? "Edit Terms & Conditions" : "Create Terms & Conditions"}</DialogTitle>
          <DialogDescription>Manage the content, status, and version details for your organization.</DialogDescription>
        </DialogHeader>
        <form onSubmit={(event) => void submit(event)} className="space-y-5">
          {error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{error}</p>}
          <FormField label="Title" name="terms-title" value={title} onChange={(event) => setTitle(event.target.value)} required maxLength={500} placeholder="Terms of Service" />
          <MarkdownInput label="Content" name="terms-body" value={body} onChange={setBody} required rows={12} placeholder="Write the Terms & Conditions content" />

          <div className="grid gap-4 sm:grid-cols-2">
            <FormField label="Version label" name="terms-version" value={versionLabel} onChange={(event) => setVersionLabel(event.target.value)} maxLength={100} placeholder="v1.0" />
            <FormField label="Effective date" name="terms-effective-from" type="date" value={effectiveFrom} onChange={(event) => setEffectiveFrom(event.target.value)} />
            <FormField label="Jurisdiction" name="terms-jurisdiction" value={jurisdiction} onChange={(event) => setJurisdiction(event.target.value)} maxLength={200} placeholder="Indonesia" />
            <FormField label="Locale" name="terms-locale" value={locale} onChange={(event) => setLocale(event.target.value)} maxLength={40} placeholder="en-US" />
            <div>
              <label className="field-label" htmlFor="terms-status">Status</label>
              <select id="terms-status" value={status} onChange={(event) => setStatus(event.target.value as "draft" | "published")} className="h-11 w-full rounded-lg border border-input bg-card px-3 outline-none focus:border-primary">
                <option value="draft">Draft</option>
                <option value="published">Published</option>
              </select>
            </div>
            <div>
              <label className="field-label" htmlFor="terms-previous-version">Previous version</label>
              <select id="terms-previous-version" value={previousVersionId} onChange={(event) => setPreviousVersionId(event.target.value)} className="h-11 w-full rounded-lg border border-input bg-card px-3 outline-none focus:border-primary">
                <option value="">None</option>
                {documents.filter((document) => document.id !== item?.id).map((document) => (
                  <option key={document.id} value={document.id}>{document.title}{document.versionLabel ? ` · ${document.versionLabel}` : ""}</option>
                ))}
              </select>
            </div>
          </div>
          <ChannelPicker channels={channels} selectedIds={channelIds} onChange={setChannelIds} />
          <DialogFooter>
            <Button type="button" variant="outline" disabled={busy} onClick={onClose}>Cancel</Button>
            <Button type="submit" disabled={busy}>{busy ? "Saving…" : item ? "Save changes" : "Create document"}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
