"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { useFeatureFlags } from "./feature-flags-provider"
import { toast } from "sonner"

import { getPOs, requestSignatures } from "../service"
import { getColumns } from "./po-table-columns"
import { ContractDetail } from "@/db/schema/contract"
import { PoTableToolbarActions } from "./po-table-toolbar-actions"
import { SignatureRequestModal } from "./sign-request-dialog"

interface ItemsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getPOs>>,
    ]
  >
}

// Interface for signing party
interface SigningParty {
  signerEmail: string;
  signerName: string;
  signerPosition: string;
  signerType: "REQUESTER" | "VENDOR";
  vendorContactId?: number;
}

export function PoListsTable({ promises }: ItemsTableProps) {
  const { featureFlags } = useFeatureFlags()
  
  const [{ data, pageCount }] = 
    React.use(promises)
    
  const [rowAction, setRowAction] = 
    React.useState<DataTableRowAction<ContractDetail> | null>(null)
    
  // State for signature request modal
  const [signatureModalOpen, setSignatureModalOpen] = React.useState(false)
  const [selectedContract, setSelectedContract] = React.useState<ContractDetail | null>(null)
  
  // Handle row actions
  React.useEffect(() => {
    if (!rowAction) return
    
    if (rowAction.type === "signature") {
      // Open signature request modal with the selected contract
      setSelectedContract(rowAction.row.original)
      setSignatureModalOpen(true)
      setRowAction(null)
    } else if (rowAction.type === "items") {
      // Existing handler for "items" action type
      // Your existing code here
      setRowAction(null)
    }
  }, [rowAction])
  
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )
  
  // Updated handler to work with multiple signers
  const handleSignatureRequest = async (
    values: { signers: SigningParty[] },
    contractId: number
  ): Promise<void> => {
    try {
      const result = await requestSignatures({
        contractId,
        signers: values.signers
      });
      
      // Handle the result
      if (result.success) {
        toast.success(result.message || "Signature requests sent successfully");
      } else {
        toast.error(result.message || "Failed to send signature requests");
      }
    } catch (error) {
      console.error("Error sending signature requests:", error);
      toast.error("An error occurred while sending the signature requests");
    }
  }

  const filterFields: DataTableFilterField<ContractDetail>[] = [
    // Your existing filter fields
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<ContractDetail>[] = [
    {
      id: "contractNo",
      label: "Contract No",
      type: "text",
    },
    {
      id: "contractName",
      label: "Contract Name",
      type: "text",
    },
    {
      id: "createdAt",
      label: "Created At",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "Updated At",
      type: "date",
    },
  ]
  
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <PoTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>
      
      {/* Enhanced Dual Signature Request Modal */}
      {selectedContract && (
        <SignatureRequestModal
          contract={selectedContract}
          open={signatureModalOpen}
          onOpenChange={setSignatureModalOpen}
          onSubmit={handleSignatureRequest}
        />
      )}
    </>
  )
}