"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 { FaqWriteValues } from "./content-contract";
import { ChannelPicker, MarkdownInput } from "./content-fields";
import type { ContentChannel, FaqRecord } from "./types";

export function FaqEditorDialog({
  item,
  channels,
  open,
  busy,
  onClose,
  onSave,
}: {
  item: FaqRecord | null;
  channels: ContentChannel[];
  open: boolean;
  busy: boolean;
  onClose: () => void;
  onSave: (values: FaqWriteValues) => Promise<void>;
}) {
  const [question, setQuestion] = useState(item?.question ?? "");
  const [answer, setAnswer] = useState(item?.answer ?? "");
  const [channelIds, setChannelIds] = useState<string[]>(item?.channelIds ?? []);
  const [error, setError] = useState("");

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    try {
      await onSave({ question, answer, channelIds });
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Unable to save this FAQ.");
    }
  }

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && !busy && onClose()}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>{item ? "Edit FAQ" : "Create FAQ"}</DialogTitle>
          <DialogDescription>Changes are saved to the FAQ content 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="Question"
            name="faq-question"
            value={question}
            onChange={(event) => setQuestion(event.target.value)}
            required
            maxLength={1000}
            placeholder="Enter the FAQ question"
          />
          <MarkdownInput
            label="Answer"
            name="faq-answer"
            value={answer}
            onChange={setAnswer}
            required
            rows={8}
            placeholder="Write the answer"
          />
          <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 FAQ"}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
