"use client";

import { useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { MapPin } from "lucide-react";
import { Field } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { parseFinancialInput, type FinancialOptions } from "./contract";
import { financialFetch } from "./dialog";
import { SearchablePicker } from "./searchable-picker";

export type InvestmentLocation = { value: string; label: string; currency: string };

export function InvestmentForm({
  location,
  groups,
  onClose,
  onSaved,
}: {
  location: InvestmentLocation;
  groups: FinancialOptions;
  onClose: () => void;
  onSaved: () => void;
}) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [groupId, setGroupId] = useState("");
  const [error, setError] = useState("");
  const submitting = useRef(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting.current) return;
    const fields = new FormData(event.currentTarget);
    const percentage = fields.get("percentage");
    const amount = fields.get("total_investment");
    const payload = parseFinancialInput("create-investment", {
      location_id: location.value,
      investor_group_id: groupId,
      percentage: percentage ? Number(percentage) : undefined,
      total_investment: amount ? Number(amount) : undefined,
    });
    if (!payload) {
      setError("Choose an investor group, enter a positive investment amount, and enter a percentage from 0 to 100.");
      return;
    }
    submitting.current = true;
    setSaving(true);
    setError("");
    try {
      await financialFetch("investor-investments", "POST", payload);
      onSaved();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "The investment could not be saved.");
    } finally {
      submitting.current = false;
      setSaving(false);
    }
  }

  return (
    <Dialog open onOpenChange={(open) => { if (!open && !submitting.current) onClose(); }}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-lg" showCloseButton={!saving}>
        <DialogHeader>
          <DialogTitle>Create investment</DialogTitle>
          <DialogDescription>Assign an investor group and record its investment for this location.</DialogDescription>
        </DialogHeader>
        <div className="flex items-center gap-3 rounded-lg border bg-muted/40 p-3">
          <MapPin aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
          <div className="min-w-0">
            <p className="text-xs text-muted-foreground">Location</p>
            <p className="break-words font-medium">{location.label}</p>
          </div>
        </div>
        <form onSubmit={submit} className="space-y-5">
          <fieldset disabled={saving} className="space-y-4">
            <SearchablePicker
              name="investor_group_id"
              label="Investor group"
              choices={groups}
              disabled={saving}
              retry={() => router.refresh()}
              onValueChange={setGroupId}
            />
            <div className="grid gap-4 sm:grid-cols-2">
              <Field
                label={location.currency ? `Total investment (${location.currency})` : "Total investment"}
                name="total_investment"
                type="number"
                min="0.01"
                step="any"
                required
              />
              <Field label="Percentage (%)" name="percentage" type="number" min={0} max={100} step="any" required />
            </div>
          </fieldset>
          {error && <p role="alert" className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</p>}
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose} disabled={saving}>Cancel</Button>
            <Button type="submit" disabled={saving || !groupId || !!groups.error}>
              {saving ? "Creating…" : "Create investment"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
