"use client";

import { useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import useSWR from "swr";
import { Table, Card, Button, Spin, Alert } from "antd";
import { EyeTwoTone, EditTwoTone } from "@ant-design/icons";

import PageHead from "@/app/Components/PageHead";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function KycLists() {
  const router = useRouter();

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);

  const {
    data: getData,
    error,
    isLoading,
  } = useSWR(
    `/api/kyc?page=${currentPage}&limit=${pageSize}&orderby_created=true`,
    fetcher
  );

  const tableData =
    getData?.data?.map((item, index) => ({
      ...item,
      key: item.kyc_id || index,
    })) || [];

  const columns = [
    {
      title: "Customer ID",
      dataIndex: "customerId",
      key: "customerId",
    },
    {
      title: "Legal Name",
      dataIndex: "legal_name",
      key: "legal_name",
    },
    {
      title: "Trade Name",
      dataIndex: "trade_name",
      key: "trade_name",
    },
    {
      title: "Entity Type",
      dataIndex: "entity_type",
      key: "entity_type",
    },
    {
      title: "Incorporation Country",
      dataIndex: "incorporation_country",
      key: "incorporation_country",
    },
    {
      title: "Primary Contact",
      dataIndex: "primary_name",
      key: "primary_name",
    },
    {
      title: "Email",
      dataIndex: "primary_email",
      key: "primary_email",
    },
    {
      title: "Created At",
      dataIndex: "created_at",
      key: "created_at",
    },
    {
      title: "Actions",
      key: "actions",
      render: (_, record) => (
        <>
          <Button
            type="text"
            icon={<EyeTwoTone />}
            onClick={() => router.push(`/jhjkaghjasadsadfdssbda67asd87asdg85fsd43hjadgta/${record.kyc_id}`)}
          />
        </>
      ),
    },
  ];

  return (
    <>
      <PageHead title="KYC List" />
      <div className="large-container sm:pt-5">
        <Card
          styles={{
            body: { padding: 0 },
          }}
        >
          {isLoading ? (
            <div className="p-4 text-center">
              <Spin />
            </div>
          ) : error ? (
            <div className="p-4">
              <Alert message="Failed to load data" type="error" />
            </div>
          ) : (
            <Table
              bordered
              columns={columns}
              dataSource={tableData}
              pagination={{
                current: currentPage,
                pageSize,
                total: getData?.pagination?.totalRecords || 0,
                onChange: (page) => setCurrentPage(page),
                showSizeChanger: false,
              }}
              size="small"
              scroll={{ x: "max-content" }}
            />
          )}
        </Card>
      </div>
    </>
  );
}
