"use client";

import { useState } from "react";
import { Field, SelectField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import {
  parseInvestorGroupInput,
  type InvestorGroup,
  type InvestorGroupInput,
} from "./investor-model";

export function InvestorGroupForm({
  initial,
  onSave,
  onCancel,
}: {
  initial: InvestorGroup | null;
  onSave: (input: InvestorGroupInput) => Promise<void>;
  onCancel: () => void;
}) {
  const [name, setName] = useState(initial?.name ?? "");
  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 = parseInvestorGroupInput({ name, active });
        if (!input) {
          setError("Enter a valid group name and status.");
          return;
        }
        setError("");
        setPending(true);
        try {
          await onSave(input);
        } catch (issue) {
          setError(
            issue instanceof Error
              ? issue.message
              : "The investor group could not be saved. Please try again.",
          );
        } finally {
          setPending(false);
        }
      }}
    >
      <fieldset disabled={pending} className="grid gap-4">
        <Field
          label="Group name"
          value={name}
          onChange={(event) => setName(event.target.value)}
          required
          maxLength={100}
          autoComplete="off"
        />
        <SelectField
          label="Status"
          value={active ? "Active" : "Inactive"}
          options={["Active", "Inactive"]}
          onChange={(event) => setActive(event.target.value === "Active")}
        />
      </fieldset>
      {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…"
            : initial
              ? "Save Changes"
              : "Create Group"}
        </Button>
      </div>
    </form>
  );
}
