import { BuildTable } from "@/components/blocks/Table/table";
import type { CoreBookingUnitGuest } from "@/lib/features/bookings/types";
import { Flex, Text } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconFileDescription } from "@tabler/icons-react";
import type { MRT_ColumnDef, MRT_RowData } from "mantine-react-table";
import { useMemo, useState } from "react";
import GuestDrawer from "./guestDrawer";
import SendEDMAction from "./sendEDMAction";

const GuestDetails: React.FC<{
  guests: CoreBookingUnitGuest[];
  unitId?: string;
}> = ({ guests, unitId }) => {
  const [opened, { open, close }] = useDisclosure(false);
  const [selectedGuest, setSelectedGuest] =
    useState<CoreBookingUnitGuest | null>(null);

  // Optional: track sent state in parent too (useful if table re-renders)
  const [sentMap, setSentMap] = useState<Record<number, boolean>>({});

  const handleRowClick = (rowData: MRT_RowData) => {
    const row = rowData as CoreBookingUnitGuest;
    setSelectedGuest(row);
    open();
  };

  const columns = useMemo<MRT_ColumnDef<CoreBookingUnitGuest>[]>(() => {
    return [
      {
        header: "Account ID",
        accessorKey: "details.AccountID",
        minSize: 200,
      },
      {
        header: "First Name",
        accessorKey: "details.FirstName",
        minSize: 200,
      },
      {
        header: "Last Name",
        accessorKey: "details.LastName",
        minSize: 200,
      },
      {
        header: "Email Address",
        accessorKey: "details.Email",
        minSize: 200,
      },
      {
        header: "Ownership Type",
        accessorFn: (row) =>
          row.details.IsOwner ? "LEGAL OWNER" : "FAMILY MEMBER",
        minSize: 200,
      },
      {
        header: "Send EDM",
        minSize: 120,
        accessorFn: (row) => {
          const memberRecordID = row.member_id ?? null;

          return (
            <SendEDMAction
              unitId={unitId}
              memberRecordID={memberRecordID}
              onSent={(id) =>
                setSentMap((prev) => ({
                  ...prev,
                  [id]: true,
                }))
              }
            />
          );
        },
      },
    ];
  }, [unitId, sentMap]);

  return (
    <Flex direction={"column"} gap={10}>
      <Flex gap={4} align={"center"}>
        <IconFileDescription size={18} />
        <Text fz={14} fw={600}>
          Guest Details
        </Text>
      </Flex>

      <BuildTable
        data={guests}
        columns={columns}
        totalRows={guests?.length}
        needPagination={false}
        enableSearch={false}
        onRowClick={handleRowClick}
      />

      <GuestDrawer
        opened={opened}
        close={close}
        selectedGuest={selectedGuest}
      />
    </Flex>
  );
};

export default GuestDetails;