"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { createTfpContractAction } from "@/lib/actions/admin";
import type { TfpContractData } from "@/models/Contract";

const SHOOTING_KINDS = ["Portrait", "Cosplay", "Fashion / Lifestyle", "Event / Convention"];
const IMAGE_COUNTS = ["ca. 3-5 final bearbeitete Bilder", "ca. 5-10 final bearbeitete Bilder", "ca. 10-15 final bearbeitete Bilder", "Nach Absprache"];
const PHOTOGRAPHER_USAGE = ["Website / Online-Portfolio", "digitale oder gedruckte Präsentationen", "Social Media", "Wettbewerbe / Ausstellungen", "Print-Portfolio", "interne Archivierung"];
const CHANNELS = ["Website / Portfolio", "Google-Unternehmensprofil", "Instagram", "Facebook", "X / Twitter", "Discord", "Bluesky", "TikTok", "Print-Portfolio", "Wettbewerbe / Ausstellungen"];
const STYLIST_USAGE = ["eigenes Portfolio", "Social Media", "Webseite", "nur nach Einzel-Freigabe"];

function CheckboxGroup({
  options,
  values,
  onChange,
}: {
  options: string[];
  values: string[];
  onChange: (next: string[]) => void;
}) {
  return (
    <div className="flex flex-wrap gap-2">
      {options.map((opt) => {
        const checked = values.includes(opt);
        return (
          <button
            key={opt}
            type="button"
            onClick={() => onChange(checked ? values.filter((v) => v !== opt) : [...values, opt])}
            className={`text-xs rounded-full px-3 py-1.5 border transition-colors ${
              checked ? "border-white text-white bg-white/10" : "border-white/15 text-[var(--rk-ink-muted)] hover:border-white/40"
            }`}
          >
            {opt}
          </button>
        );
      })}
    </div>
  );
}

function calcIsMinor(birthdate: string): boolean {
  if (!birthdate) return false;
  const dob = new Date(birthdate);
  const now = new Date();
  let age = now.getFullYear() - dob.getFullYear();
  const m = now.getMonth() - dob.getMonth();
  if (m < 0 || (m === 0 && now.getDate() < dob.getDate())) age--;
  return age < 18;
}

export function TfpContractForm({
  orderId,
  defaults,
}: {
  orderId: string;
  defaults: {
    characterOrConcept: string;
    eventLocation: string;
    datePeriod: string;
    instagramHandle: string;
    clientStreet: string;
    clientPostCode: string;
    clientCity: string;
  };
}) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);

  const [modelBirthdate, setModelBirthdate] = useState("");
  // Vorbefüllt aus der Rechnungsadresse des Kunden-Kontos (falls hinterlegt)
  // — spart erneutes Eintippen, bleibt aber änderbar (Model ≠ Auftraggeber:in
  // ist möglich, z. B. bei einer Buchung für eine andere Person).
  const [modelStreet, setModelStreet] = useState(defaults.clientStreet);
  const [modelPostCode, setModelPostCode] = useState(defaults.clientPostCode);
  const [modelCity, setModelCity] = useState(defaults.clientCity);
  const [modelInstagram, setModelInstagram] = useState(defaults.instagramHandle);

  const [hasStylist, setHasStylist] = useState(false);
  const [stylistName, setStylistName] = useState("");
  const [stylistStreet, setStylistStreet] = useState("");
  const [stylistPostCode, setStylistPostCode] = useState("");
  const [stylistCity, setStylistCity] = useState("");
  const [stylistInstagram, setStylistInstagram] = useState("");
  const [stylistUsage, setStylistUsage] = useState<string[]>([]);
  const [stylistCredit, setStylistCredit] = useState("");

  const [shootingTheme, setShootingTheme] = useState(defaults.characterOrConcept);
  const [shootingLocation, setShootingLocation] = useState(defaults.eventLocation);
  const [shootingDate, setShootingDate] = useState(defaults.datePeriod);
  const [shootingKinds, setShootingKinds] = useState<string[]>([]);

  const [finalImageCount, setFinalImageCount] = useState(IMAGE_COUNTS[0]);
  const [photographerUsage, setPhotographerUsage] = useState<string[]>(["Website / Online-Portfolio", "Social Media"]);
  const [publicationChannels, setPublicationChannels] = useState<string[]>(["Instagram"]);
  const [publicationRestrictions, setPublicationRestrictions] = useState("");
  const [creditPreference, setCreditPreference] = useState<"nennen" | "nicht_nennen" | "nach_absprache">("nennen");
  const [creditHandle, setCreditHandle] = useState(defaults.instagramHandle);
  const [photographerCreditRequired, setPhotographerCreditRequired] = useState(true);

  const [companionAllowed, setCompanionAllowed] = useState(true);
  const [specialAgreements, setSpecialAgreements] = useState("");

  const [guardian1Name, setGuardian1Name] = useState("");
  const [guardian1Street, setGuardian1Street] = useState("");
  const [guardian1PostCode, setGuardian1PostCode] = useState("");
  const [guardian1City, setGuardian1City] = useState("");
  const [guardian1Contact, setGuardian1Contact] = useState("");
  const [guardian2Name, setGuardian2Name] = useState("");
  const [guardian2Street, setGuardian2Street] = useState("");
  const [guardian2PostCode, setGuardian2PostCode] = useState("");
  const [guardian2City, setGuardian2City] = useState("");
  const [guardian2Contact, setGuardian2Contact] = useState("");

  const isMinor = useMemo(() => calcIsMinor(modelBirthdate), [modelBirthdate]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);

    const guardians = [];
    if (isMinor && guardian1Name)
      guardians.push({ name: guardian1Name, street: guardian1Street, postCode: guardian1PostCode, city: guardian1City, contact: guardian1Contact, relation: "" });
    if (isMinor && guardian2Name)
      guardians.push({ name: guardian2Name, street: guardian2Street, postCode: guardian2PostCode, city: guardian2City, contact: guardian2Contact, relation: "" });

    const data: TfpContractData = {
      modelBirthdate,
      modelStreet,
      modelPostCode,
      modelCity,
      modelInstagram,
      stylist: hasStylist
        ? { name: stylistName, street: stylistStreet, postCode: stylistPostCode, city: stylistCity, instagram: stylistInstagram, usage: stylistUsage, credit: stylistCredit }
        : null,
      shootingTheme,
      shootingLocation,
      shootingDate,
      shootingKinds,
      finalImageCount,
      photographerUsage,
      publicationChannels,
      publicationRestrictions,
      creditPreference,
      creditHandle,
      photographerCreditRequired,
      companionAllowed,
      specialAgreements,
      isMinor,
      guardians,
    };

    await createTfpContractAction(orderId, data);
    setSaving(false);
    router.push(`/de/admin/orders/${orderId}`);
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-8 max-w-2xl">
      <Section title="Model">
        <TextInput label="Geburtsdatum" type="date" value={modelBirthdate} onChange={setModelBirthdate} />
        <AddressInputs
          street={modelStreet}
          postCode={modelPostCode}
          city={modelCity}
          onStreet={setModelStreet}
          onPostCode={setModelPostCode}
          onCity={setModelCity}
        />
        <TextInput label="Instagram" value={modelInstagram} onChange={setModelInstagram} />
        {isMinor && (
          <p className="text-xs text-amber-400 mt-1">
            Model ist laut Geburtsdatum minderjährig — Unterschrift der Erziehungsberechtigten wird beim Signieren verlangt.
          </p>
        )}
      </Section>

      {isMinor && (
        <Section title="Erziehungsberechtigte">
          <p className="text-xs text-[var(--rk-ink-muted)] mb-2">Vertreter/in 1 (Pflicht), Vertreter/in 2 optional.</p>
          <TextInput label="Name (1)" value={guardian1Name} onChange={setGuardian1Name} />
          <AddressInputs
            street={guardian1Street}
            postCode={guardian1PostCode}
            city={guardian1City}
            onStreet={setGuardian1Street}
            onPostCode={setGuardian1PostCode}
            onCity={setGuardian1City}
          />
          <TextInput label="Kontakt (1)" value={guardian1Contact} onChange={setGuardian1Contact} />
          <TextInput label="Name (2)" value={guardian2Name} onChange={setGuardian2Name} />
          <AddressInputs
            street={guardian2Street}
            postCode={guardian2PostCode}
            city={guardian2City}
            onStreet={setGuardian2Street}
            onPostCode={setGuardian2PostCode}
            onCity={setGuardian2City}
          />
          <TextInput label="Kontakt (2)" value={guardian2Contact} onChange={setGuardian2Contact} />
        </Section>
      )}

      <Section title="Stylist/in (optional)">
        <label className="flex items-center gap-2 text-sm mb-3">
          <input type="checkbox" checked={hasStylist} onChange={(e) => setHasStylist(e.target.checked)} />
          Styling-Person beteiligt
        </label>
        {hasStylist && (
          <>
            <TextInput label="Name" value={stylistName} onChange={setStylistName} />
            <AddressInputs
              street={stylistStreet}
              postCode={stylistPostCode}
              city={stylistCity}
              onStreet={setStylistStreet}
              onPostCode={setStylistPostCode}
              onCity={setStylistCity}
            />
            <TextInput label="Instagram" value={stylistInstagram} onChange={setStylistInstagram} />
            <FieldLabel>Nutzung erlaubt</FieldLabel>
            <CheckboxGroup options={STYLIST_USAGE} values={stylistUsage} onChange={setStylistUsage} />
            <TextInput label="Credit" value={stylistCredit} onChange={setStylistCredit} />
          </>
        )}
      </Section>

      <Section title="Shooting">
        <TextInput label="Thema / Charakter" value={shootingTheme} onChange={setShootingTheme} />
        <TextInput label="Ort / Event" value={shootingLocation} onChange={setShootingLocation} />
        <TextInput label="Datum / Zeitraum" value={shootingDate} onChange={setShootingDate} />
        <FieldLabel>Art</FieldLabel>
        <CheckboxGroup options={SHOOTING_KINDS} values={shootingKinds} onChange={setShootingKinds} />
      </Section>

      <Section title="Bildauswahl">
        <select
          value={finalImageCount}
          onChange={(e) => setFinalImageCount(e.target.value)}
          className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm w-full"
        >
          {IMAGE_COUNTS.map((c) => (
            <option key={c} value={c}>{c}</option>
          ))}
        </select>
      </Section>

      <Section title="Nutzungsrechte Fotograf">
        <CheckboxGroup options={PHOTOGRAPHER_USAGE} values={photographerUsage} onChange={setPhotographerUsage} />
      </Section>

      <Section title="Veröffentlichung">
        <FieldLabel>Kanäle</FieldLabel>
        <CheckboxGroup options={CHANNELS} values={publicationChannels} onChange={setPublicationChannels} />
        <TextInput label="Einschränkungen" value={publicationRestrictions} onChange={setPublicationRestrictions} />
        <FieldLabel>Credit-Wunsch</FieldLabel>
        <select
          value={creditPreference}
          onChange={(e) => setCreditPreference(e.target.value as typeof creditPreference)}
          className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm w-full mb-3"
        >
          <option value="nennen">Nennen/Verlinken</option>
          <option value="nicht_nennen">Nicht nennen/verlinken</option>
          <option value="nach_absprache">Je nach Bild/Plattform nach Absprache</option>
        </select>
        <TextInput label="Handle für Credit" value={creditHandle} onChange={setCreditHandle} />
        <label className="flex items-center gap-2 text-sm mt-1">
          <input
            type="checkbox"
            checked={photographerCreditRequired}
            onChange={(e) => setPhotographerCreditRequired(e.target.checked)}
          />
          Model muss Rakku Photography bei eigener Veröffentlichung nennen/verlinken (soweit auf der Plattform möglich)
        </label>
      </Section>

      <Section title="Sonstiges">
        <label className="flex items-center gap-2 text-sm mb-3">
          <input type="checkbox" checked={companionAllowed} onChange={(e) => setCompanionAllowed(e.target.checked)} />
          Begleitperson erlaubt
        </label>
        <FieldLabel>Besondere Vereinbarungen</FieldLabel>
        <textarea
          value={specialAgreements}
          onChange={(e) => setSpecialAgreements(e.target.value)}
          rows={3}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm w-full"
        />
      </Section>

      <button
        type="submit"
        disabled={saving}
        className="self-start border border-white/30 rounded-lg px-6 py-2.5 text-xs uppercase tracking-[0.2em] hover:border-white disabled:opacity-50"
      >
        {saving ? "…" : "Vertrag als Entwurf anlegen"}
      </button>
    </form>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="border border-white/10 rounded-xl p-5">
      <h2 className="text-sm font-semibold mb-4">{title}</h2>
      {children}
    </div>
  );
}

function FieldLabel({ children }: { children: React.ReactNode }) {
  return <p className="text-xs uppercase tracking-[0.08em] text-[var(--rk-ink-muted)] mb-1.5">{children}</p>;
}

// Straße/PLZ/Ort getrennt statt einer Freitext-Zeile — konsistent mit der
// Rechnungsadresse im Kundenkonto und auf Rechnungen (siehe lib/orderConstants.ts formatAddress).
function AddressInputs({
  street,
  postCode,
  city,
  onStreet,
  onPostCode,
  onCity,
}: {
  street: string;
  postCode: string;
  city: string;
  onStreet: (v: string) => void;
  onPostCode: (v: string) => void;
  onCity: (v: string) => void;
}) {
  return (
    <div className="flex flex-col gap-3 mb-3">
      <TextInput label="Straße & Hausnummer" value={street} onChange={onStreet} />
      <div className="grid grid-cols-[7rem_1fr] gap-3">
        <TextInputBare label="PLZ" value={postCode} onChange={onPostCode} />
        <TextInputBare label="Ort" value={city} onChange={onCity} />
      </div>
    </div>
  );
}

// Wie TextInput, aber ohne das äußere mb-3 — wird schon vom umschließenden
// AddressInputs-Grid übernommen, sonst entsteht doppelter Abstand.
function TextInputBare({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <label className="flex flex-col gap-1 text-sm">
      <span className="text-xs uppercase tracking-[0.08em] text-[var(--rk-ink-muted)]">{label}</span>
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
      />
    </label>
  );
}

function TextInput({
  label,
  value,
  onChange,
  type = "text",
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
}) {
  return (
    <label className="flex flex-col gap-1 text-sm mb-3">
      <span className="text-xs uppercase tracking-[0.08em] text-[var(--rk-ink-muted)]">{label}</span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
      />
    </label>
  );
}
