import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import {
  TransferPartyFields,
  type TransferSponsorOption
} from "@/components/forms/transfer-party-fields";

const sponsors: TransferSponsorOption[] = [
  {
    id: "sponsor-a",
    sponsorName: "المتبرع الأول",
    orphans: [
      { id: "orphan-a", orphanName: "اليتيم الأول", caseNumber: "ORP-000001" },
      { id: "orphan-b", orphanName: "اليتيم الثاني", caseNumber: "ORP-000002" }
    ]
  },
  {
    id: "sponsor-b",
    sponsorName: "المتبرع الثاني",
    orphans: [
      { id: "orphan-c", orphanName: "اليتيم الثالث", caseNumber: "ORP-000003" }
    ]
  }
];

afterEach(cleanup);

describe("transfer sponsor and orphan fields", () => {
  it("loads only the selected sponsor's orphans and clears the orphan when sponsor changes", () => {
    render(<TransferPartyFields sponsors={sponsors} idPrefix="create-transfer" />);

    const sponsor = screen.getByLabelText("المتبرع");
    const orphan = screen.getByLabelText("اليتيم");
    expect(orphan).toBeDisabled();

    fireEvent.change(sponsor, { target: { value: "sponsor-a" } });
    expect(orphan).toBeEnabled();
    expect(within(orphan).getByRole("option", { name: "اليتيم الأول - ORP-000001" })).toBeInTheDocument();
    expect(within(orphan).getByRole("option", { name: "اليتيم الثاني - ORP-000002" })).toBeInTheDocument();
    expect(within(orphan).queryByRole("option", { name: "اليتيم الثالث - ORP-000003" })).not.toBeInTheDocument();

    fireEvent.change(orphan, { target: { value: "orphan-b" } });
    expect(orphan).toHaveValue("orphan-b");

    fireEvent.change(sponsor, { target: { value: "sponsor-b" } });
    expect(orphan).toHaveValue("");
    expect(within(orphan).getByRole("option", { name: "اليتيم الثالث - ORP-000003" })).toBeInTheDocument();
    expect(within(orphan).queryByRole("option", { name: "اليتيم الثاني - ORP-000002" })).not.toBeInTheDocument();
  });

  it("preselects the current sponsor and orphan in an edit form", () => {
    render(
      <TransferPartyFields
        sponsors={sponsors}
        idPrefix="edit-transfer"
        defaultSponsorId="sponsor-a"
        defaultOrphanId="orphan-b"
      />
    );

    expect(screen.getByLabelText("المتبرع")).toHaveValue("sponsor-a");
    expect(screen.getByLabelText("اليتيم")).toHaveValue("orphan-b");
  });

  it("automatically selects the first linked orphan in the create form", () => {
    render(
      <TransferPartyFields
        sponsors={sponsors}
        idPrefix="create-transfer"
        autoSelectFirstOrphan
      />
    );

    const sponsor = screen.getByLabelText("المتبرع");
    const orphan = screen.getByLabelText("اليتيم");

    fireEvent.change(sponsor, { target: { value: "sponsor-b" } });
    expect(orphan).toHaveValue("orphan-c");

    fireEvent.change(sponsor, { target: { value: "sponsor-a" } });
    expect(orphan).toHaveValue("orphan-a");
  });
});
