"use client";

import { useMemo, useState } from "react";
import { Label } from "@/components/ui/label";

export type TransferOrphanOption = {
  id: string;
  orphanName: string;
  caseNumber: string;
};

export type TransferSponsorOption = {
  id: string;
  sponsorName: string;
  orphans: TransferOrphanOption[];
};

type TransferPartyFieldsProps = {
  sponsors: TransferSponsorOption[];
  idPrefix: string;
  defaultSponsorId?: string;
  defaultOrphanId?: string;
  autoSelectFirstOrphan?: boolean;
};

export function TransferPartyFields({
  sponsors,
  idPrefix,
  defaultSponsorId = "",
  defaultOrphanId = "",
  autoSelectFirstOrphan = false
}: TransferPartyFieldsProps) {
  const initialSponsor = sponsors.find((sponsor) => sponsor.id === defaultSponsorId);
  const [sponsorId, setSponsorId] = useState(initialSponsor?.id ?? "");
  const [orphanId, setOrphanId] = useState(
    initialSponsor?.orphans.some((orphan) => orphan.id === defaultOrphanId)
      ? defaultOrphanId
      : ""
  );
  const linkedOrphans = useMemo(
    () => sponsors.find((sponsor) => sponsor.id === sponsorId)?.orphans ?? [],
    [sponsors, sponsorId]
  );
  const sponsorFieldId = `${idPrefix}-sponsor`;
  const orphanFieldId = `${idPrefix}-orphan`;

  return (
    <>
      <div>
        <Label htmlFor={sponsorFieldId}>المتبرع</Label>
        <select
          id={sponsorFieldId}
          name="sponsorId"
          value={sponsorId}
          onChange={(event) => {
            const nextSponsorId = event.target.value;
            const nextOrphans =
              sponsors.find((sponsor) => sponsor.id === nextSponsorId)?.orphans ?? [];
            setSponsorId(nextSponsorId);
            setOrphanId(
              autoSelectFirstOrphan && nextOrphans.length > 0
                ? nextOrphans[0].id
                : ""
            );
          }}
          required
          className="h-11 w-full min-w-0 rounded-md border bg-white px-3 text-sm"
        >
          <option value="">اختر المتبرع</option>
          {sponsors.map((sponsor) => (
            <option key={sponsor.id} value={sponsor.id}>
              {sponsor.sponsorName}
            </option>
          ))}
        </select>
      </div>
      <div>
        <Label htmlFor={orphanFieldId}>اليتيم</Label>
        <select
          id={orphanFieldId}
          name="orphanId"
          value={orphanId}
          onChange={(event) => setOrphanId(event.target.value)}
          required
          disabled={!sponsorId}
          className="h-11 w-full min-w-0 rounded-md border bg-white px-3 text-sm disabled:cursor-not-allowed disabled:bg-[var(--surface-muted)] disabled:text-[var(--ink-faint)]"
        >
          <option value="">{sponsorId ? "اختر اليتيم" : "اختر المتبرع أولاً"}</option>
          {linkedOrphans.map((orphan) => (
            <option key={orphan.id} value={orphan.id}>
              {orphan.orphanName} - {orphan.caseNumber}
            </option>
          ))}
        </select>
      </div>
    </>
  );
}
