"use client";

import { ColumnDef } from "@tanstack/react-table";
import {
  DataTable,
  DTExtraParamsProps,
  IconTextButtonWithTooltip,
} from "ikoncomponents";
import { RefreshCcw } from "lucide-react";
import { useEffect, useState } from "react";

/**
 * Type for Integration data
 */
export interface ConnectorData {
  connectorId: string;
  connectorName: string;
  appName: string;
}

function IntegrationTable() {
  const [data, setData] = useState<ConnectorData[]>([]);
  const [loading, setLoading] = useState(true);

  // Dummy fetch (replace with API call)
  useEffect(() => {
    const fetchConnectors = async () => {
      try {
        setLoading(true);

        // Replace this with your actual API
        const response: ConnectorData[] = [
          {
            connectorId: "1",
            connectorName: "Salesforce Connector",
            appName: "Sales CRM",
          },
          {
            connectorId: "2",
            connectorName: "Zoho Connector",
            appName: "Project Management",
          },
        ];

        setData(response);
      } catch (error) {
        console.error("Failed to fetch integrations", error);
        setData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchConnectors();
  }, []);

  const handleSync = () => {
    console.log("Sync button clicked");
    //  Call sync API here
  };

  const columns: ColumnDef<ConnectorData>[] = [
    {
      accessorKey: "connectorName",
      header: () => <div className="text-center">Connector Name</div>,
      cell: ({ row }) => (
        <span className="font-medium">
          {row.original.connectorName}
        </span>
      ),
    },
    {
      accessorKey: "appName",
      header: () => <div className="text-center">App Name</div>,
      cell: ({ row }) => <span>{row.original.appName}</span>,
    },
  ];

  const extraParams: DTExtraParamsProps = {
    extraTools: [
      <IconTextButtonWithTooltip
        key="sync"
        tooltipContent="Sync Data"
        variant="outline"
        onClick={handleSync}
      >
        <RefreshCcw className="h-4 w-4" />
      </IconTextButtonWithTooltip>,
    ],
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-[250px]">
        <div className="animate-spin rounded-full h-10 w-10 border-t-4 border-blue-500" />
      </div>
    );
  }

  return <DataTable columns={columns} data={data} extraParams={extraParams} />;
}

export default IntegrationTable;