"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import { Button } from "@/app/shadcn_components/ui/button";

const btn =
  "rounded-xl border border-gray-200 bg-white px-4 py-2 text-sm font-semibold text-brandblue transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-45";

/**
 * Client shell around the read-only config sheet: rename (label only),
 * use-as-template, view-in-reporting, and the guarded delete zone.
 */
export function DetailActions({
  portfolioId,
  scenarioId,
  name: initialName,
  modelled,
  plansCount,
  statusPill,
  meta,
  children,
}: {
  portfolioId: string;
  scenarioId: string;
  name: string;
  modelled: boolean;
  plansCount: number;
  statusPill: React.ReactNode;
  meta: string;
  children: React.ReactNode;
}) {
  const router = useRouter();
  const [name, setName] = useState(initialName);
  const [editing, setEditing] = useState(false);
  const [draftName, setDraftName] = useState(initialName);
  const [error, setError] = useState<string | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteConfirmation, setDeleteConfirmation] = useState("");
  const deleteConfirmed = deleteConfirmation.trim().toLowerCase() === "delete";

  const rename = useMutation({
    mutationFn: async (newName: string) => {
      const res = await fetch(
        `/api/portfolio/${portfolioId}/scenarios/${scenarioId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name: newName }),
        },
      );
      if (!res.ok) throw new Error((await res.json()).error ?? "Rename failed");
      return newName;
    },
    onSuccess: (newName) => {
      setName(newName);
      setEditing(false);
      setError(null);
      router.refresh();
    },
    onError: (e: Error) => setError(e.message),
  });

  const remove = useMutation({
    mutationFn: async () => {
      const res = await fetch(
        `/api/portfolio/${portfolioId}/scenarios/${scenarioId}`,
        { method: "DELETE" },
      );
      if (!res.ok) throw new Error((await res.json()).error ?? "Delete failed");
    },
    onSuccess: () => router.push(`/portfolio/${portfolioId}/scenarios`),
    onError: (e: Error) => {
      setError(e.message);
      setDeleteOpen(false);
    },
  });

  return (
    <>
      <div className="mb-1 flex items-center justify-between gap-4">
        {editing ? (
          <div className="flex min-w-0 flex-1 items-center gap-2">
            <input
              autoFocus
              value={draftName}
              maxLength={120}
              onChange={(e) => setDraftName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && draftName.trim())
                  rename.mutate(draftName.trim());
                if (e.key === "Escape") setEditing(false);
              }}
              className="min-w-0 flex-1 max-w-[460px] rounded-xl border border-brandmidblue px-3 py-1.5 font-manrope text-lg font-extrabold text-brandblue shadow-[0_0_0_3px_rgba(57,67,183,.12)] outline-none"
            />
            <button
              className="rounded-xl px-4 py-2 text-sm font-semibold text-white"
              style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
              disabled={!draftName.trim() || rename.isLoading}
              onClick={() => rename.mutate(draftName.trim())}
            >
              Save
            </button>
            <button
              className="px-2 py-2 text-sm font-semibold text-brandmidblue"
              onClick={() => setEditing(false)}
            >
              Cancel
            </button>
          </div>
        ) : (
          <h2 className="min-w-0 truncate font-manrope text-2xl font-extrabold tracking-tight text-brandblue">
            {name}
            <button
              title="Rename scenario"
              aria-label="Rename scenario"
              className="ml-2 rounded-lg px-2 py-0.5 align-[2px] text-[15px] text-gray-400 hover:bg-brandlightblue hover:text-brandmidblue"
              onClick={() => {
                setDraftName(name);
                setEditing(true);
              }}
            >
              ✎
            </button>
          </h2>
        )}
        {statusPill}
      </div>
      <div className="mb-5 text-[13px] tabular-nums text-gray-400">{meta}</div>

      {children}

      <div className="mt-5 flex flex-wrap items-center gap-3">
        <Link
          href={modelled ? `/portfolio/${portfolioId}/reporting` : "#"}
          aria-disabled={!modelled}
          className={`${btn} ${modelled ? "" : "pointer-events-none opacity-45"}`}
        >
          View results in Reporting →
        </Link>
        <Link href={`/portfolio/${portfolioId}/scenarios/new?from=${scenarioId}`} className={btn}>
          Use as template
        </Link>
        {!modelled && (
          <span className="text-[13px] text-gray-400">
            Results will appear here once modelling has run against this scenario.
          </span>
        )}
      </div>

      <div className="mt-6 flex flex-wrap items-center gap-3.5 border-t border-gray-100 pt-4">
        {modelled ? (
          <>
            <button className={`${btn} !text-red-800/70`} disabled>
              Delete scenario
            </button>
            <span className="max-w-[52ch] text-[13px] text-gray-400">
              There are{" "}
              <b className="font-semibold text-gray-600">
                {plansCount.toLocaleString("en-GB")} properties
              </b>{" "}
              with plans in this scenario, so it can&apos;t be deleted. Contact a
              Domna administrator to remove the plans first.
            </span>
          </>
        ) : (
          <>
            <button
              className={`${btn} border-red-100 !text-red-800 hover:!bg-red-50`}
              onClick={() => {
                setDeleteConfirmation("");
                setDeleteOpen(true);
              }}
            >
              Delete scenario
            </button>
            <span className="max-w-[52ch] text-[13px] text-gray-400">
              Nothing has been modelled against this scenario — deleting removes
              only the configuration.
            </span>
          </>
        )}
      </div>
      {error && <div className="mt-3 text-[13px] text-red-800">{error}</div>}

      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent className="max-w-md">
          <DialogTitle className="font-manrope text-lg font-extrabold text-brandblue">
            Delete “{name}”?
          </DialogTitle>
          <p className="text-sm text-gray-600">
            Nothing has been modelled against this scenario — deleting removes
            only the configuration. This can&apos;t be undone.
          </p>
          <div>
            <label
              htmlFor="delete-confirmation"
              className="mb-1.5 block text-sm text-gray-600"
            >
              To confirm, type <strong className="text-brandblue">delete</strong>
            </label>
            <input
              id="delete-confirmation"
              autoFocus
              type="text"
              value={deleteConfirmation}
              placeholder="delete"
              onChange={(e) => setDeleteConfirmation(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && deleteConfirmed && !remove.isLoading)
                  remove.mutate();
              }}
              className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm outline-none transition focus:border-red-300 focus:shadow-[0_0_0_3px_rgba(185,28,28,.10)]"
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteOpen(false)}>
              Cancel
            </Button>
            <Button
              className="bg-red-700 hover:bg-red-800"
              disabled={!deleteConfirmed || remove.isLoading}
              onClick={() => remove.mutate()}
            >
              {remove.isLoading ? "Deleting…" : "Delete scenario"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
