"use client";

import { useEffect, useState } from "react";
import { Select } from "@/components/life/Controls";
import { LifeNotice, LifeSkeleton } from "@/components/life/LifeStatus";
import Icon from "@/components/ui/Icon";
import { ApiError } from "@/lib/api/client";
import { submitInvestment } from "@/lib/api/services";
import { useSectorsStore } from "@/store/services";

// Seeded fact titles use an em-dash; visible copy avoids them.
const clean = (s: string) => s.replace(/\s*—\s*/g, ": ");

type Fields = { name: string; email: string; phone: string; sector_id: string; message: string };
const EMPTY: Fields = { name: "", email: "", phone: "", sector_id: "", message: "" };

/** Investment sectors beside the request form. The sector list also feeds the form's sector picker. */
export default function InvestSectors() {
  const store = useSectorsStore();

  useEffect(() => {
    if (store.status === "idle") void store.load();
  }, [store.status, store.load]);

  const loading = store.status === "idle" || store.status === "loading";

  return (
    <div className="iv">
      <section aria-labelledby="sectors-h">
        <h2 id="sectors-h" className="lfd-h2">Sectors</h2>
        <LifeNotice status={store.status} error={store.error} hasFallback={false} onRetry={() => void store.load()} />
        {loading && store.items.length === 0 ? (
          <LifeSkeleton />
        ) : (
          <ul className="iv-sectors">
            {store.items.map((s) => (
              <li key={s.id}>
                <h3 className="sv-h3">{s.name}</h3>
                {s.description && <p>{s.description}</p>}
                {s.facts.length > 0 && (
                  <ul className="iv-facts">
                    {[...s.facts]
                      .sort((a, b) => a.sort_order - b.sort_order)
                      .map((f) => (
                        <li key={f.id}>
                          <strong>{clean(f.title)}</strong> {f.body}
                        </li>
                      ))}
                  </ul>
                )}
              </li>
            ))}
          </ul>
        )}
      </section>
      <InvestForm sectors={store.items.map((s) => ({ value: String(s.id), label: s.name }))} />
    </div>
  );
}

function InvestForm({ sectors }: { sectors: { value: string; label: string }[] }) {
  const [f, setF] = useState<Fields>(EMPTY);
  const [errors, setErrors] = useState<Record<string, string[]>>({});
  const [failure, setFailure] = useState<string | null>(null);
  const [state, setState] = useState<"idle" | "sending" | "sent">("idle");

  const set = (k: keyof Fields) => (v: string) => {
    setF((p) => ({ ...p, [k]: v }));
    setErrors(({ [k]: _drop, ...rest }) => rest);
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setState("sending");
    setFailure(null);
    setErrors({});
    try {
      await submitInvestment({
        name: f.name.trim(),
        email: f.email.trim(),
        phone: f.phone.trim() || undefined,
        message: f.message.trim(),
        sector_id: f.sector_id ? Number(f.sector_id) : undefined,
      });
      setState("sent");
      setF(EMPTY);
    } catch (err) {
      setState("idle");
      if (err instanceof ApiError && err.errors) setErrors(err.errors);
      else setFailure(err instanceof ApiError ? err.message : "Something went wrong. Please try again.");
    }
  };

  if (state === "sent") {
    return (
      <section className="iv-form iv-sent" aria-live="polite">
        <Icon name="check_circle" />
        <h2 className="lfd-h2">Request received</h2>
        <p>Thank you. The investment team will reply by email.</p>
        <button type="button" className="btn btn-outline btn-sm" onClick={() => setState("idle")}>
          Send another request
        </button>
      </section>
    );
  }

  const field = (k: keyof Fields, label: string, input: React.ReactNode) => (
    <label className="lf-field">
      <span className="lf-label">{label}</span>
      {input}
      {errors[k] && (
        <small className="iv-err" id={`iv-${k}-err`}>
          {errors[k][0]}
        </small>
      )}
    </label>
  );
  const attrs = (k: keyof Fields) => ({
    className: "lf-input",
    value: f[k],
    onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => set(k)(e.target.value),
    "aria-invalid": errors[k] ? true : undefined,
    "aria-describedby": errors[k] ? `iv-${k}-err` : undefined,
  });

  return (
    <form className="iv-form" onSubmit={onSubmit} aria-labelledby="iv-form-h">
      <h2 id="iv-form-h" className="lfd-h2">Talk to the investment team</h2>
      {field("name", "Full name", <input {...attrs("name")} required maxLength={150} autoComplete="name" />)}
      {field("email", "Email", <input {...attrs("email")} type="email" required maxLength={255} autoComplete="email" />)}
      {field("phone", "Phone (optional)", <input {...attrs("phone")} type="tel" maxLength={30} autoComplete="tel" />)}
      <div className="iv-select">
        <Select label="Sector" value={f.sector_id} options={[{ value: "", label: "No specific sector" }, ...sectors]} onChange={set("sector_id")} />
        {errors.sector_id && <small className="iv-err">{errors.sector_id[0]}</small>}
      </div>
      {field("message", "Message", <textarea {...attrs("message")} required maxLength={5000} rows={5} />)}
      {failure && (
        <p className="iv-err" role="alert">
          {failure}
        </p>
      )}
      <button type="submit" className="btn btn-rose" disabled={state === "sending"}>
        {state === "sending" ? "Sending" : "Send request"}
      </button>
    </form>
  );
}
