"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { AnnotationEditor } from "./AnnotationEditor";
import type { Category, Feature, Screenshot } from "@/lib/types";

interface Props {
  feature: Feature;
  categories: Category[];
  isNew?: boolean;
}

export function FeatureEditor({ feature, categories, isNew }: Props) {
  const router = useRouter();
  const [form, setForm] = useState(feature);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeShotId, setActiveShotId] = useState<string | null>(
    feature.screenshots[0]?.id ?? null
  );

  const activeShot =
    form.screenshots.find((s) => s.id === activeShotId) ??
    form.screenshots[0] ??
    null;

  async function save() {
    setSaving(true);
    setError(null);
    try {
      const res = await fetch(
        isNew ? "/api/features" : `/api/features/${form.id}`,
        {
          method: isNew ? "POST" : "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(form),
        }
      );
      if (!res.ok) throw new Error("Save failed");
      const saved = (await res.json()) as Feature;
      router.push(`/features/${saved.id}`);
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Save failed");
    } finally {
      setSaving(false);
    }
  }

  async function onUpload(files: FileList | null) {
    if (!files?.length) return;
    setUploading(true);
    setError(null);
    try {
      const uploaded: Screenshot[] = [];
      for (const file of Array.from(files)) {
        const data = new FormData();
        data.append("file", file);
        const res = await fetch("/api/uploads", { method: "POST", body: data });
        if (!res.ok) throw new Error(`Upload failed for ${file.name}`);
        uploaded.push(await res.json());
      }
      setForm((prev) => {
        const screenshots = [...prev.screenshots, ...uploaded];
        return { ...prev, screenshots };
      });
      setActiveShotId(uploaded[uploaded.length - 1]?.id ?? activeShotId);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setUploading(false);
    }
  }

  function updateShotAnnotations(shotId: string, annotations: Screenshot["annotations"]) {
    setForm((prev) => ({
      ...prev,
      screenshots: prev.screenshots.map((s) =>
        s.id === shotId ? { ...s, annotations } : s
      ),
    }));
  }

  function removeShot(shotId: string) {
    setForm((prev) => {
      const screenshots = prev.screenshots.filter((s) => s.id !== shotId);
      return { ...prev, screenshots };
    });
    if (activeShotId === shotId) {
      setActiveShotId(null);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <Link
            href="/features"
            className="text-sm text-[var(--muted)] hover:text-[var(--ink)]"
          >
            ← Features
          </Link>
          <h1 className="mt-2 text-2xl font-semibold tracking-tight text-[var(--ink)]">
            {isNew ? "New feature" : "Edit feature"}
          </h1>
          {form.isDemo && (
            <span className="mt-2 inline-block rounded-md bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800">
              DEMO EXAMPLE
            </span>
          )}
        </div>
        <div className="flex gap-2">
          <Link href={`/preview/${form.id}`} className="btn-secondary">
            Preview page
          </Link>
          <button type="button" onClick={save} disabled={saving} className="btn-primary">
            {saving ? "Saving…" : "Save feature"}
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          {error}
        </div>
      )}

      <section className="panel space-y-4 p-5">
        <Field label="Feature name">
          <input
            className="input"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            placeholder="Feature name"
          />
        </Field>
        <Field label="Category">
          <select
            className="input"
            value={form.categoryId}
            onChange={(e) => setForm({ ...form, categoryId: e.target.value })}
          >
            {categories.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Description">
          <textarea
            className="input min-h-28"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
            placeholder="What does this feature do?"
          />
        </Field>
        <Field label="Business benefit">
          <textarea
            className="input min-h-24"
            value={form.businessBenefit}
            onChange={(e) =>
              setForm({ ...form, businessBenefit: e.target.value })
            }
            placeholder="Why does this matter to the business?"
          />
        </Field>
      </section>

      <section className="panel space-y-4 p-5">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="text-lg font-semibold text-[var(--ink)]">
              Screenshots
            </h2>
            <p className="text-sm text-[var(--muted)]">
              Upload one or more images, then annotate with arrows, rectangles,
              or circles.
            </p>
          </div>
          <label className="btn-secondary cursor-pointer">
            {uploading ? "Uploading…" : "Upload screenshots"}
            <input
              type="file"
              accept="image/*"
              multiple
              className="hidden"
              disabled={uploading}
              onChange={(e) => onUpload(e.target.files)}
            />
          </label>
        </div>

        {form.screenshots.length === 0 ? (
          <div className="rounded-xl border border-dashed border-[var(--line)] px-4 py-10 text-center text-sm text-[var(--muted)]">
            No screenshots yet. Upload images to annotate them.
          </div>
        ) : (
          <>
            <div className="flex flex-wrap gap-3">
              {form.screenshots.map((shot) => (
                <button
                  key={shot.id}
                  type="button"
                  onClick={() => setActiveShotId(shot.id)}
                  className={`overflow-hidden rounded-lg border ${
                    activeShot?.id === shot.id
                      ? "border-[var(--accent)] ring-2 ring-[var(--accent)]/30"
                      : "border-[var(--line)]"
                  }`}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={`/api/uploads/${shot.id}`}
                    alt={shot.originalName}
                    className="h-20 w-32 object-cover"
                  />
                </button>
              ))}
            </div>

            {activeShot && (
              <div className="space-y-3">
                <div className="flex items-center justify-between gap-2">
                  <div className="text-sm text-[var(--muted)]">
                    {activeShot.originalName} · {activeShot.annotations.length}{" "}
                    annotation
                    {activeShot.annotations.length === 1 ? "" : "s"}
                  </div>
                  <button
                    type="button"
                    onClick={() => removeShot(activeShot.id)}
                    className="text-sm text-[var(--danger)]"
                  >
                    Remove screenshot
                  </button>
                </div>
                <AnnotationEditor
                  screenshot={activeShot}
                  onChange={(annotations) =>
                    updateShotAnnotations(activeShot.id, annotations)
                  }
                />
              </div>
            )}
          </>
        )}
      </section>
    </div>
  );
}

function Field({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label className="block space-y-1.5">
      <span className="text-sm font-medium text-[var(--ink)]">{label}</span>
      {children}
    </label>
  );
}
