// apps/web/components/ops/EpicPanel.tsx
"use client";

import { useState, useEffect, useTransition } from "react";
import { useRouter } from "next/navigation";
import { LocalTime } from "@/components/ui/LocalTime";
import { createEpic, updateEpic, type EpicOverlap } from "@/lib/actions/backlog";
import {
  validateEpicInput,
  EPIC_STATUSES,
  type EpicInput,
  type EpicWithRelations,
  type PortfolioForSelect,
} from "@/lib/backlog";
import { AGENT_NAME_MAP } from "@/lib/agent-routing";

type Props = {
  isOpen: boolean;
  onClose: () => void;
  epic?: EpicWithRelations;
  portfolios: PortfolioForSelect[];
};

function emptyForm(): EpicInput {
  return { title: "", status: "open", portfolioIds: [] };
}

export function EpicPanel({ isOpen, onClose, epic, portfolios }: Props) {
  const router = useRouter();
  const [form, setForm] = useState<EpicInput>(emptyForm);
  const [error, setError] = useState<string | null>(null);
  const [overlaps, setOverlaps] = useState<EpicOverlap[]>([]);
  const [isPending, startTransition] = useTransition();

  useEffect(() => {
    if (epic) {
      setForm({
        title:        epic.title,
        description:  epic.description ?? "",
        status:       epic.status as EpicInput["status"],
        portfolioIds: epic.portfolios.map((p) => p.portfolioId),
      });
    } else {
      setForm(emptyForm());
    }
    setError(null);
    setOverlaps([]);
  }, [epic, isOpen]);

  function togglePortfolio(portfolioId: string) {
    setForm((prev) => {
      const already = prev.portfolioIds.includes(portfolioId);
      return {
        ...prev,
        portfolioIds: already
          ? prev.portfolioIds.filter((id) => id !== portfolioId)
          : [...prev.portfolioIds, portfolioId],
      };
    });
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const validationError = validateEpicInput(form);
    if (validationError) { setError(validationError); return; }
    setError(null);

    startTransition(async () => {
      try {
        if (epic) {
          await updateEpic(epic.id, form);
          router.refresh();
          onClose();
        } else {
          const result = await createEpic(form);
          router.refresh();
          if (result.similarEpics.length > 0) {
            setOverlaps(result.similarEpics);
          } else {
            onClose();
          }
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : "Something went wrong");
      }
    });
  }

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/40 z-40"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Panel */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-8 pointer-events-none">
      <div className="w-3/4 max-h-[85vh] bg-[var(--dpf-surface-1)] border border-[var(--dpf-border)] rounded-lg flex flex-col shadow-2xl pointer-events-auto">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--dpf-border)]">
          <h2 className="text-sm font-semibold text-[var(--dpf-text)]">
            {epic ? "Edit Epic" : "New Epic"}
          </h2>
          <button
            onClick={onClose}
            className="text-[var(--dpf-muted)] hover:text-[var(--dpf-text)] text-lg leading-none"
          >
            ×
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto px-5 py-4 flex flex-col gap-4">
          {/* Title */}
          <label className="flex flex-col gap-1">
            <span className="text-[10px] uppercase tracking-widest text-[var(--dpf-muted)]">Title *</span>
            <input
              type="text"
              value={form.title}
              onChange={(e) => setForm((prev) => ({ ...prev, title: e.target.value }))}
              className="bg-[var(--dpf-surface-2)] border border-[var(--dpf-border)] rounded px-3 py-2 text-sm text-[var(--dpf-text)] placeholder:text-[var(--dpf-muted)] focus:outline-none focus:border-[var(--dpf-accent)]"
              placeholder="What is this initiative?"
              required
            />
          </label>

          {/* Description */}
          <label className="flex flex-col gap-1">
            <span className="text-[10px] uppercase tracking-widest text-[var(--dpf-muted)]">Description</span>
            <textarea
              value={form.description ?? ""}
              onChange={(e) => setForm((prev) => ({ ...prev, description: e.target.value }))}
              rows={3}
              className="bg-[var(--dpf-surface-2)] border border-[var(--dpf-border)] rounded px-3 py-2 text-sm text-[var(--dpf-text)] placeholder:text-[var(--dpf-muted)] focus:outline-none focus:border-[var(--dpf-accent)] resize-none"
              placeholder="Optional context…"
            />
          </label>

          {/* Status */}
          <label className="flex flex-col gap-1">
            <span className="text-[10px] uppercase tracking-widest text-[var(--dpf-muted)]">Status</span>
            <select
              value={form.status}
              onChange={(e) => setForm((prev) => ({ ...prev, status: e.target.value as EpicInput["status"] }))}
              className="bg-[var(--dpf-surface-2)] border border-[var(--dpf-border)] rounded px-3 py-2 text-sm text-[var(--dpf-text)] focus:outline-none focus:border-[var(--dpf-accent)]"
            >
              {EPIC_STATUSES.map((s) => (
                <option key={s} value={s}>
                  {s.charAt(0).toUpperCase() + s.slice(1)}
                </option>
              ))}
            </select>
          </label>

          {/* Portfolios */}
          <div className="flex flex-col gap-2">
            <span className="text-[10px] uppercase tracking-widest text-[var(--dpf-muted)]">Portfolios</span>
            {portfolios.map((p) => (
              <label key={p.id} className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={form.portfolioIds.includes(p.id)}
                  onChange={() => togglePortfolio(p.id)}
                  className="accent-[var(--dpf-accent)]"
                />
                <span className="text-sm text-[var(--dpf-text)]">{p.name}</span>
              </label>
            ))}
          </div>

          {error && (
            <p className="text-xs text-red-400">{error}</p>
          )}

          {overlaps.length > 0 && (
            <div className="rounded border border-yellow-600/50 bg-yellow-900/20 p-3 space-y-2">
              <p className="text-xs text-yellow-400 font-semibold">
                Epic created — but similar epics already exist:
              </p>
              <ul className="space-y-1">
                {overlaps.map((o) => (
                  <li key={o.epicId} className="text-xs text-yellow-300/80">
                    <span className="font-mono">{o.epicId}</span>{" "}
                    <span className="text-[var(--dpf-text)]">{o.title}</span>{" "}
                    <span className="text-[var(--dpf-muted)]">({o.status})</span>
                  </li>
                ))}
              </ul>
              <p className="text-[10px] text-[var(--dpf-muted)]">
                Review these for potential overlap. You can merge or close duplicates from the Ops backlog.
              </p>
              <button
                type="button"
                onClick={onClose}
                className="text-xs text-yellow-400 underline hover:text-yellow-300"
              >
                Dismiss
              </button>
            </div>
          )}
        </form>

        {/* Metadata (read-only) */}
        {epic && (
          <div className="px-5 py-3 border-t border-[var(--dpf-border)] space-y-1">
            <p className="text-[10px] text-[var(--dpf-muted)]">
              Created: <LocalTime value={epic.createdAt} />
              {epic.submittedBy ? ` by ${epic.submittedBy.email}` : ""}
              {epic.agentId ? ` (${AGENT_NAME_MAP[epic.agentId] ?? epic.agentId})` : ""}
            </p>
            <p className="text-[10px] text-[var(--dpf-muted)]">
              Completed: <LocalTime value={epic.completedAt} />
            </p>
          </div>
        )}

        {/* Footer */}
        <div className="px-5 py-4 border-t border-[var(--dpf-border)] flex gap-2">
          <button
            type="button"
            onClick={onClose}
            className="flex-1 py-2 rounded border border-[var(--dpf-border)] text-xs text-[var(--dpf-muted)] hover:text-[var(--dpf-text)]"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={isPending}
            className="flex-1 py-2 rounded bg-[var(--dpf-accent)] text-xs text-white font-semibold hover:opacity-90 disabled:opacity-50"
          >
            {isPending ? "Saving…" : epic ? "Save Changes" : "Create Epic"}
          </button>
        </div>
      </div>
      </div>
    </>
  );
}
