"use client";
import { useState } from "react";
import { Field, SelectField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import {
  parseInvestorInput,
  type Investor,
  type InvestorInput,
} from "./investor-model";

export function InvestorForm({
  initial,
  mode,
  onSave,
  onCancel,
}: {
  initial: Investor | null;
  mode: "api" | "preview";
  onSave: (input: InvestorInput) => Promise<void>;
  onCancel: () => void;
}) {
  const [firstname, setFirstname] = useState(initial?.firstname ?? "");
  const [lastname, setLastname] = useState(initial?.lastname ?? "");
  const [email, setEmail] = useState(initial?.email ?? "");
  const [phone, setPhone] = useState(initial?.phone ?? "");
  const [active, setActive] = useState(initial?.active ?? true);
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);
  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault();
        const input = parseInvestorInput(
          {
            firstname,
            lastname,
            active,
            ...(!initial ? { email, phone } : {}),
          },
          initial ? "PATCH" : "POST",
        );
        if (!input) {
          setError(
            "Enter a first and last name, a valid email and phone number.",
          );
          return;
        }
        setError("");
        setPending(true);
        try {
          await onSave(input);
        } catch (issue) {
          setError(
            issue instanceof Error
              ? issue.message
              : "The investor could not be saved. Please try again.",
          );
        } finally {
          setPending(false);
        }
      }}
    >
      <fieldset disabled={pending} className="grid gap-4 sm:grid-cols-2">
        <Field
          label="First Name"
          value={firstname}
          onChange={(event) => setFirstname(event.target.value)}
          required
          maxLength={100}
          autoComplete="given-name"
        />
        <Field
          label="Last Name"
          value={lastname}
          onChange={(event) => setLastname(event.target.value)}
          required
          maxLength={100}
          autoComplete="family-name"
        />
        <Field
          label="Email"
          type="email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          required
          disabled={!!initial}
          maxLength={255}
          autoComplete="email"
        />
        <Field
          label="Phone"
          type="tel"
          value={phone}
          onChange={(event) => setPhone(event.target.value)}
          required
          disabled={!!initial}
          maxLength={32}
          autoComplete="tel"
        />
        <SelectField
          label="Status"
          value={active ? "Active" : "Inactive"}
          options={["Active", "Inactive"]}
          onChange={(event) => setActive(event.target.value === "Active")}
        />
      </fieldset>
      <p className="mt-4 text-xs text-muted-foreground">
        Manage group membership from Investor Groups.{" "}
        {initial
          ? "This form updates the investor’s name and status."
          : "New accounts are created with the Investor role."}
      </p>
      {error && (
        <p role="alert" className="mt-4 text-sm text-destructive">
          {error}
        </p>
      )}
      <div className="mt-6 flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={pending}
        >
          Cancel
        </Button>
        <Button disabled={pending}>
          {pending
            ? "Saving…"
            : mode === "preview"
              ? "Save Preview"
              : initial
                ? "Save Changes"
                : "Create Investor"}
        </Button>
      </div>
    </form>
  );
}
