"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, ContractDetailParsed, Envelope } from "@/db/schema/contract"
import { PoTableToolbarActions } from "./po-table-toolbar-actions"
import { SignatureRequestModal } from "./sign-request-dialog"
import { EsignStatusDialog } from "./esign-dialog"
import { ItemsDialog } from "./item-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 transformContractData(data: ContractDetail[]): ContractDetailParsed[] {
  return data.map((contract) => {
    let parsedEnvelopes: Envelope[] = [];
    let parsedItems = [];
    
    try {
      // Check if envelopes is a string that needs parsing
      if (typeof contract.envelopes === "string") {
        parsedEnvelopes = JSON.parse(contract.envelopes);
      } else if (Array.isArray(contract.envelopes)) {
        // If it's already an array, use it directly
        parsedEnvelopes = contract.envelopes as unknown as Envelope[];
      }
      
      // Check if items is a string that needs parsing
      if (typeof contract.items === "string") {
        parsedItems = JSON.parse(contract.items);
      } else if (Array.isArray(contract.items)) {
        // If it's already an array, use it directly
        parsedItems = contract.items;
      }
    } catch (err) {
      console.error("Error parsing JSON", err);
    }

    // Return a new object with all properties from the original contract
    // but replace envelopes and items with their parsed versions
    return {
      ...contract,
      envelopes: parsedEnvelopes,
      items: parsedItems
    } as ContractDetailParsed;
  });
}
export function PoListsTable({ promises }: ItemsTableProps) {
  const { featureFlags } = useFeatureFlags()

  const [rawData, setRawData] = React.useState<{
    data: ContractDetail[];
    pageCount: number;
  }>({ data: [], pageCount: 0 });

  // Add state for transformed data
  const [transformedData, setTransformedData] = React.useState<{
    data: ContractDetailParsed[];
    pageCount: number;
  }>({ data: [], pageCount: 0 });

  console.log(rawData)
  console.log(transformedData)

  // Load raw data from promises
  React.useEffect(() => {
    promises.then(([result]) => {
      console.log(result.data)

      setRawData(result);
      // Transform the data
      setTransformedData({
        data: transformContractData(result.data),
        pageCount: result.pageCount
      });
    });
  }, [promises]);

  const [rowAction, setRowAction] =
    React.useState<DataTableRowAction<ContractDetailParsed> | null>(null)

  // State for signature request modal
  const [signatureModalOpen, setSignatureModalOpen] = React.useState(false)
  const [signatureDetailOpen, setSignatureDetailOpen] = React.useState(false)
  const [itemsOpen, setItemsOpen] = React.useState(false)
  const [selectedContract, setSelectedContract] = React.useState<ContractDetailParsed | 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") {
      setSelectedContract(rowAction.row.original)
      setItemsOpen(true)
      setRowAction(null)
    } else if (rowAction.type === "esign-detail") {
      setSignatureDetailOpen(true)
      setSelectedContract(rowAction.row.original)
      console.log("E-sign details for contract:", rowAction.row.original);
      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<ContractDetailParsed>[] = [
    // Your existing filter fields
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<ContractDetailParsed>[] = [
    {
      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: transformedData.data, // Use the transformed data
    columns,
    pageCount: transformedData.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>

      <EsignStatusDialog
        open={signatureDetailOpen}
        onOpenChange={setSignatureDetailOpen}
        po={selectedContract}
      />

      <ItemsDialog
        open={itemsOpen}
        onOpenChange={setItemsOpen}
        po={selectedContract}
      />


      {/* Enhanced Dual Signature Request Modal */}
      {selectedContract && (
        <SignatureRequestModal
          contract={selectedContract}
          open={signatureModalOpen}
          onOpenChange={setSignatureModalOpen}
          onSubmit={handleSignatureRequest}
        />
      )}
    </>
  )
}