import { useState, type FormEvent, type KeyboardEvent } from "react";
import { Link } from "react-router-dom";
import {
  ChevronRight,
  Loader2,
  Settings as SettingsIcon,
  Sparkles,
  Shuffle,
  Flame,
  Wand2,
} from "lucide-react";
import { EqualizerIcon } from "./EqualizerIcon";
import type { InputValues, Language, Vocals } from "../lib/types";
import { formatElapsed, useElapsed } from "../lib/useElapsed";
import { randomStyle } from "../lib/llm";
import { useToast } from "../lib/toast";

export type { InputValues };

const LANGUAGES: { value: Language; label: string }[] = [
  { value: "English", label: "English" },
  { value: "Deutsch", label: "Deutsch" },
  { value: "Español", label: "Español" },
  { value: "Français", label: "Français" },
  { value: "Italiano", label: "Italiano" },
  { value: "Português", label: "Português" },
  { value: "Polski", label: "Polski" },
  { value: "Other", label: "Other" },
];

const EXAMPLE_IDEAS: { text: string; mood: string; vocals: Vocals }[] = [
  {
    text: "melancholic lo-fi house beat for a rainy sunday morning",
    mood: "melancholic",
    vocals: "instrumental",
  },
  {
    text: "euphoric summer pop anthem with a singalong chorus",
    mood: "euphoric",
    vocals: "vocals",
  },
  {
    text: "tense cinematic underscore for a thriller chase scene",
    mood: "tense",
    vocals: "instrumental",
  },
  {
    text: "dreamy ambient ballad about missing someone far away",
    mood: "longing",
    vocals: "vocals",
  },
];

interface InputPanelProps {
  values: InputValues;
  onChange: (next: InputValues) => void;
  onSubmit: () => void;
  loading: boolean;
  disabled?: boolean;
  cancelButton?: React.ReactNode;
}

export function InputPanel({
  values,
  onChange,
  onSubmit,
  loading,
  disabled,
  cancelButton,
}: InputPanelProps) {
  const [styleLoading, setStyleLoading] = useState<null | "normal" | "crazy">(
    null,
  );
  const [optionsOpen, setOptionsOpen] = useState(false);
  const elapsed = useElapsed(loading);
  const toast = useToast();

  const set = <K extends keyof InputValues>(key: K, value: InputValues[K]) =>
    onChange({ ...values, [key]: value });

  const canSubmit = !loading && !disabled && values.idea.trim().length > 0;

  const submit = (e?: FormEvent) => {
    e?.preventDefault();
    if (canSubmit) onSubmit();
  };

  const onCmdEnter = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
      e.preventDefault();
      submit();
    }
  };

  const fillExample = () => {
    const ex = EXAMPLE_IDEAS[Math.floor(Math.random() * EXAMPLE_IDEAS.length)];
    onChange({
      ...values,
      idea: ex.text,
      mood: values.mood || ex.mood,
      vocals: ex.vocals,
    });
  };

  const handleStyleRandom = async (mode: "normal" | "crazy") => {
    if (styleLoading) return;
    const ctrl = new AbortController();
    setStyleLoading(mode);
    try {
      const style = await randomStyle(mode, ctrl.signal);
      onChange({ ...values, style_hint: style });
    } catch (err) {
      if (err instanceof DOMException && err.name === "AbortError") return;
      toast.error(
        err instanceof Error
          ? err.message
          : `Could not generate a ${mode} style — please try again`,
      );
    } finally {
      setStyleLoading((curr) => (curr === mode ? null : curr));
    }
  };

  return (
    <form onSubmit={submit} className="space-y-6">
      {/* Brand */}
      <div className="flex items-center gap-2.5">
        <EqualizerIcon size={22} className="shrink-0" />
        <div>
          <h1 className="text-lg font-semibold tracking-tight gradient-text leading-none">
            MelodyMuse
          </h1>
        </div>
      </div>

      {/* Main textarea */}
      <div>
        <div className="flex items-center justify-between mb-2">
          <label
            htmlFor="idea"
            className="text-[11px] font-medium uppercase tracking-wider text-fg-muted"
          >
            Music idea
          </label>
          <button
            type="button"
            onClick={fillExample}
            className="inline-flex items-center gap-1 text-[11px] text-fg-muted hover:text-fg transition-colors"
            title="Fill the input with a random example"
          >
            <Shuffle className="w-3 h-3" />
            Try an example
          </button>
        </div>
        <textarea
          id="idea"
          value={values.idea}
          onChange={(e) => set("idea", e.target.value)}
          onKeyDown={onCmdEnter}
          rows={4}
          placeholder="Describe your music idea…"
          className="textarea text-[15px] leading-relaxed"
          required
        />
        <p className="mt-1.5 text-[11px] text-fg-muted">
          <kbd className="px-1 py-0.5 rounded bg-bg-hover border border-border font-mono">
            {isMac() ? "⌘" : "Ctrl"}+Enter
          </kbd>{" "}
          to generate
        </p>
      </div>

      {/* Options — collapsible, subtle */}
      <div className="rounded-xl border border-border bg-bg-card/30">
        <button
          type="button"
          onClick={() => setOptionsOpen((v) => !v)}
          className="w-full flex items-center justify-between gap-2 px-4 py-3 text-sm font-medium text-fg-muted hover:text-fg transition-colors"
          aria-expanded={optionsOpen}
        >
          <span className="flex items-center gap-2">
            <ChevronRight
              className={`w-3.5 h-3.5 transition-transform ${optionsOpen ? "rotate-90" : ""}`}
            />
            Options
          </span>
          <span className="text-[11px] text-fg-muted">
            {summaryCount(values) > 0
              ? summaryCount(values) + " set"
              : "defaults"}
          </span>
        </button>

        {optionsOpen && (
          <div className="px-4 pb-4 pt-1 space-y-4 border-t border-border">
            <div>
              <label
                htmlFor="language"
                className="block text-[11px] font-medium uppercase tracking-wider text-fg-muted mb-1.5"
              >
                Language
              </label>
              <select
                id="language"
                value={values.language}
                onChange={(e) => set("language", e.target.value as Language)}
                className="input"
              >
                {LANGUAGES.map((l) => (
                  <option key={l.value} value={l.value}>
                    {l.label}
                  </option>
                ))}
              </select>
              {values.language === "Other" && (
                <input
                  type="text"
                  className="input mt-2"
                  placeholder="e.g. 日本語, Türkçe, Русский"
                  value={values.customLanguage}
                  onChange={(e) => set("customLanguage", e.target.value)}
                />
              )}
            </div>

            <StyleField
              value={values.style_hint}
              loading={styleLoading}
              onChange={(v) => set("style_hint", v)}
              onRandom={handleStyleRandom}
              onCmdEnter={onCmdEnter}
            />

            <div>
              <label
                htmlFor="mood"
                className="block text-[11px] font-medium uppercase tracking-wider text-fg-muted mb-1.5"
              >
                Mood{" "}
                <span className="text-fg-muted/70 normal-case font-normal">
                  (optional)
                </span>
              </label>
              <input
                id="mood"
                type="text"
                placeholder="e.g. melancholic, euphoric, tense…"
                value={values.mood}
                onChange={(e) => set("mood", e.target.value)}
                className="input"
              />
            </div>

            <div>
              <span className="block text-[11px] font-medium uppercase tracking-wider text-fg-muted mb-1.5">
                Vocals
              </span>
              <div className="inline-flex rounded-lg border border-border bg-bg-card p-0.5">
                <button
                  type="button"
                  onClick={() => set("vocals", "vocals")}
                  className={
                    values.vocals === "vocals"
                      ? "px-3 py-1.5 rounded-md text-sm font-medium bg-accent-primary text-white transition-colors"
                      : "px-3 py-1.5 rounded-md text-sm font-medium text-fg-muted hover:text-fg transition-colors"
                  }
                  aria-pressed={values.vocals === "vocals"}
                >
                  🎤 Vocals
                </button>
                <button
                  type="button"
                  onClick={() => set("vocals", "instrumental")}
                  className={
                    values.vocals === "instrumental"
                      ? "px-3 py-1.5 rounded-md text-sm font-medium bg-accent-primary text-white transition-colors"
                      : "px-3 py-1.5 rounded-md text-sm font-medium text-fg-muted hover:text-fg transition-colors"
                  }
                  aria-pressed={values.vocals === "instrumental"}
                >
                  🎹 Instrumental
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Generate */}
      <div className="space-y-2">
        <button
          type="submit"
          disabled={!canSubmit}
          className="w-full py-3.5 rounded-xl text-sm font-semibold text-white shadow-lg shadow-violet-900/20 transition-all duration-150 disabled:opacity-40 disabled:cursor-not-allowed disabled:shadow-none flex items-center justify-center gap-2 gradient-bg hover:brightness-110 active:brightness-95"
        >
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              Generating… {formatElapsed(elapsed)}
            </>
          ) : (
            <>
              <Sparkles className="w-4 h-4" />
              Generate song assets
            </>
          )}
        </button>
        {loading && cancelButton}
      </div>

      <div className="flex items-center justify-between text-xs">
        <Link
          to="/settings"
          className="inline-flex items-center gap-1.5 text-fg-muted hover:text-fg transition-colors"
        >
          <SettingsIcon className="w-3.5 h-3.5" />
          Settings
        </Link>
      </div>
    </form>
  );
}

function summaryCount(v: InputValues): number {
  let n = 0;
  if (v.style_hint.trim()) n++;
  if (v.mood.trim()) n++;
  if (v.vocals === "instrumental") n++;
  if (v.language !== "English") n++;
  return n;
}

interface StyleFieldProps {
  value: string;
  loading: null | "normal" | "crazy";
  onChange: (v: string) => void;
  onRandom: (mode: "normal" | "crazy") => void;
  onCmdEnter: (e: KeyboardEvent<HTMLTextAreaElement>) => void;
}

function StyleField({
  value,
  loading,
  onChange,
  onRandom,
  onCmdEnter,
}: StyleFieldProps) {
  return (
    <div>
      <label
        htmlFor="style_hint"
        className="block text-[11px] font-medium uppercase tracking-wider text-fg-muted mb-1.5"
      >
        Music style{" "}
        <span className="text-fg-muted/70 normal-case font-normal">
          (optional)
        </span>
      </label>
      <textarea
        id="style_hint"
        rows={2}
        placeholder="e.g. dark synthwave, analog pads, 110 BPM"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={onCmdEnter}
        className="textarea text-sm"
      />
      <div className="mt-2 grid grid-cols-2 gap-2">
        <button
          type="button"
          onClick={() => onRandom("normal")}
          disabled={loading !== null}
          className="inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md border border-border bg-bg-card hover:bg-bg-hover transition-colors text-xs font-medium text-fg disabled:opacity-50 disabled:cursor-not-allowed"
          title="Generate a coherent Suno-friendly style description"
        >
          {loading === "normal" ? (
            <Loader2 className="w-3 h-3 animate-spin" />
          ) : (
            <Wand2 className="w-3 h-3" />
          )}
          Surprise me
        </button>
        <button
          type="button"
          onClick={() => onRandom("crazy")}
          disabled={loading !== null}
          className="inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md border border-border bg-bg-card hover:bg-bg-hover transition-colors text-xs font-medium text-fg disabled:opacity-50 disabled:cursor-not-allowed"
          title="Generate an unusual genre mashup that still works in Suno"
        >
          {loading === "crazy" ? (
            <Loader2 className="w-3 h-3 animate-spin" />
          ) : (
            <Flame className="w-3 h-3" />
          )}
          Go crazy
        </button>
      </div>
    </div>
  );
}

function isMac(): boolean {
  if (typeof navigator === "undefined") return false;
  const p = navigator.platform || "";
  const ua = navigator.userAgent || "";
  return /Mac|iPhone|iPad|iPod/.test(p) || /Mac OS X/.test(ua);
}
