'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { UserModel } from '@/utils/types/User';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  // CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

// import PaginationComponent from '../paginationComponent/paginationComponent';

type TableCellData = {
  value: string | number | null;
  color?: 'warning' | 'success';
};

const UsersList = ({ users }: { users: UserModel[] | null }) => {
  const router = useRouter();
  // const searchParams = useSearchParams();
  // const currentPage = Number(searchParams.get('page')) || 1;
  const tableHead = [
    { column: 'Name' },
    { column: 'Email' },
    { column: 'Brand' },
    { column: 'Country' },
    { column: 'Account Type' },
    { column: 'Status' },
    { column: 'Credit' },
    { column: 'Requests Balance' },
    { column: 'Paid Subscription' },
    { column: 'Reports' },
    // { column: "Created At" },
  ];

  const [tableData, setTableData] = useState<TableCellData[][]>([]);

  useEffect(() => {
    if (users?.length) {
      const data = users.map((ele) => {
        const fullName =
          `${ele?.first_name ?? ''} ${ele?.last_name ?? ''}`.trim();

        return [
          { value: fullName || '-' },
          { value: ele?.email ?? '-' },
          { value: ele?.brand_name ?? '-' },
          { value: ele?.country?.name ?? '-' },
          { value: ele?.account_type ?? '-' },
          {
            value: ele?.is_activated ? 'Active' : 'Inactive',
            color: ele?.is_activated
              ? ('success' as const)
              : ('warning' as const),
          },
          { value: ele?.credit ?? 0 },
          { value: ele?.requests_balance ?? 0 },
          {
            value: ele?.is_paid_subscription ? 'Yes' : 'No',
            color: ele?.is_paid_subscription
              ? ('success' as const)
              : ('warning' as const),
          },
          { value: ele?.reports ?? '-' },
          // {
          //   value: ele.created_at
          //     ? dayjs(ele.created_at).format("DD/MM/YYYY")
          //     : null,
          // },
        ];
      });
      setTableData(data);
    }
  }, [users]);

  // const handlePageChange = (page: number) => {
  //   // Update URL with new page number
  //   const params = new URLSearchParams(searchParams?.toString());
  //   params.set('page', page.toString());
  //   router.push(`?${params.toString()}`);
  // };

  const renderItem = (row: TableCellData[], index: number) => {
    const userId = users?.[index]?.id;
    return (
      <TableRow
        key={index}
        onClick={() => userId && router.push(`/users/${userId}`)}
      >
        {row?.map((ele, i) => {
          return ele.color && ele.value ? (
            <TableCell key={i} className="text-start">
              <Badge variant={ele.color} appearance="outline">
                {ele.value}
              </Badge>
            </TableCell>
          ) : (
            <TableCell key={i} className="text-sm text-foreground">
              {ele.value || '-'}
            </TableCell>
          );
        })}
      </TableRow>
    );
  };

  // const totalPages = users?.length;

  return (
    <Card>
      <CardHeader>
        <CardTitle>Users Management</CardTitle>
        <Button variant="outline" onClick={() => router.push('/users/add')}>
          Create User
        </Button>
      </CardHeader>
      <CardContent className="kt-scrollable-x-auto p-0">
        <Table>
          <TableHeader>
            <TableRow className="bg-accent/60">
              {tableHead?.map((ele) => {
                return (
                  <TableHead key={ele.column} className="min-w-50 h-10">
                    {ele.column}
                  </TableHead>
                );
              })}
            </TableRow>
          </TableHeader>
          <TableBody>
            {tableData.length > 0 ? (
              tableData.map((table, index) => renderItem(table, index))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={tableHead.length}
                  className="text-center py-8 text-muted-foreground"
                >
                  No users found
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </CardContent>
      {/* <CardFooter className="justify-center">
        <PaginationComponent
          currentPage={currentPage}
          totalPages={totalPages ?? 0}
          onPageChange={handlePageChange}
        />
      </CardFooter> */}
    </Card>
  );
};

export { UsersList };
