"use client";
import { useState } from "react";
import { Field, SelectField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import { usePreviewRole } from "@/components/layout/preview-context";
import { validatePerson, type Person } from "./model";
export function PersonForm({
  initial,
  people,
  onSave,
  onCancel,
  account = false,
  groups = ["No group", "Central Partners"],
}: {
  initial: Person;
  people: readonly Person[];
  onSave: (person: Person) => void;
  onCancel: () => void;
  account?: boolean;
  groups?: readonly string[];
}) {
  const [person, setPerson] = useState(initial),
    [error, setError] = useState("");
  const role = usePreviewRole();
  function change(key: keyof Person, value: string) {
    setPerson((p) => ({ ...p, [key]: value }));
  }
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        const issue = validatePerson(person, people);
        if (issue) {
          setError(issue);
          return;
        }
        onSave({
          ...person,
          name: `${person.firstName.trim()} ${person.lastName.trim()}`,
        });
      }}
    >
      <div className="mb-6 grid gap-4 sm:grid-cols-2">
        {(
          [
            "firstName",
            "lastName",
            "email",
            "phone",
            "country",
            "city",
            "address",
          ] as const
        ).map((key, i) => (
          <Field
            key={key}
            label={
              [
                "First Name",
                "Last Name",
                "Email",
                "Phone",
                "Country",
                "City",
                "Street and Number",
              ][i]
            }
            type={key === "email" ? "email" : key === "phone" ? "tel" : "text"}
            required={!["city", "address"].includes(key)}
            value={person[key]}
            onChange={(e) => change(key, e.target.value)}
          />
        ))}
        {account ? (
          <SelectField
            label="Role"
            options={
              role === "admin"
                ? ["Admin", "Operator", "Building Management"]
                : ["Operator"]
            }
            value={person.role}
            onChange={(e) => change("role", e.target.value)}
          />
        ) : (
          <SelectField
            label="Status"
            options={["Active", "Inactive"]}
            value={person.status}
            onChange={(e) => change("status", e.target.value)}
          />
        )}
        <SelectField
          label="Organization"
          options={["TIAR"]}
          defaultValue="TIAR"
          disabled={role !== "admin"}
        />
        {person.role === "Investor" && (
          <SelectField
            label="Investor Group"
            options={groups}
            value={person.group}
            onChange={(e) => change("group", e.target.value)}
          />
        )}
      </div>
      {error && (
        <p role="alert" className="mb-4 text-destructive">
          {error}
        </p>
      )}
      <div className="flex justify-end gap-2">
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
        <Button>Save Preview</Button>
      </div>
    </form>
  );
}
