"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { TermsCategory } from "@prisma/client";
import { AdminDialog } from "@/components/ui/admin-dialog";
import { TERMS_CATEGORIES, TERMS_CATEGORY_LABEL } from "@/lib/terms";
import { createTerm, updateTerm } from "./actions";

const INPUT = "w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20";

export type TermRow = {
  id: string;
  category: TermsCategory;
  text: string;
  isActive: boolean;
};

function Fields({ term }: { term?: TermRow }) {
  return (
    <div className="space-y-3">
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Category *</label>
        <select name="category" defaultValue={term?.category ?? ""} required className={INPUT}>
          <option value="" disabled>Select a category…</option>
          {TERMS_CATEGORIES.map((c) => (
            <option key={c} value={c}>{TERMS_CATEGORY_LABEL[c]}</option>
          ))}
        </select>
      </div>
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Clause text *</label>
        <textarea name="text" defaultValue={term?.text ?? ""} rows={3} required className={INPUT} placeholder="e.g. Within 4 to 5 days" />
      </div>
    </div>
  );
}

export function AddTermButton() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault(); setPending(true); setError("");
    const result = await createTerm(new FormData(e.currentTarget));
    if ("error" in result) { setError(result.error); setPending(false); }
    else { setPending(false); setOpen(false); router.refresh(); }
  }

  return (
    <>
      <button onClick={() => setOpen(true)} className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700">
        + Add Clause
      </button>
      <AdminDialog open={open} onClose={() => setOpen(false)} title="Add T&C Clause">
        <form onSubmit={handleSubmit} className="space-y-4">
          <Fields />
          {error && <p className="text-sm text-danger-700 bg-danger-50 rounded px-3 py-2">{error}</p>}
          <div className="flex gap-3 justify-end">
            <button type="button" onClick={() => setOpen(false)} className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700">Cancel</button>
            <button type="submit" disabled={pending} className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">{pending ? "Saving…" : "Create"}</button>
          </div>
        </form>
      </AdminDialog>
    </>
  );
}

export function EditTermButton({
  term,
  open: controlledOpen,
  onOpenChange,
}: {
  term: TermRow;
  open?: boolean;
  onOpenChange?: (v: boolean) => void;
}) {
  const router = useRouter();
  const [internalOpen, setInternalOpen] = useState(false);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  const isControlled = controlledOpen !== undefined;
  const open = isControlled ? controlledOpen : internalOpen;
  const setOpen = isControlled ? (onOpenChange ?? (() => {})) : setInternalOpen;

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault(); setPending(true); setError("");
    const result = await updateTerm(term.id, new FormData(e.currentTarget));
    if ("error" in result) { setError(result.error); setPending(false); }
    else { setPending(false); setOpen(false); router.refresh(); }
  }

  return (
    <AdminDialog open={open} onClose={() => setOpen(false)} title="Edit T&C Clause">
      <form onSubmit={handleSubmit} className="space-y-4">
        <Fields term={term} />
        {error && <p className="text-sm text-danger-700 bg-danger-50 rounded px-3 py-2">{error}</p>}
        <div className="flex justify-end gap-3">
          <button type="button" onClick={() => setOpen(false)} className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700">Cancel</button>
          <button type="submit" disabled={pending} className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">{pending ? "Saving…" : "Save"}</button>
        </div>
      </form>
    </AdminDialog>
  );
}
