'use client';

import { format } from 'date-fns';
import { ru } from 'date-fns/locale';
import { CalendarIcon } from 'lucide-react';
import { useEffect, useState } from 'react';

import {
  TransactionRequest,
  TransactionResponse,
} from '@/entities/transactions/model/types';

import { useTextController } from '@/shared/language/hooks/use-text-controller';
import { Button } from '@/shared/shadcn-ui/button';
import { Calendar } from '@/shared/shadcn-ui/calendar';
import { Label } from '@/shared/shadcn-ui/label';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/shared/shadcn-ui/popover';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/shared/shadcn-ui/table';

import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from './pagination';

export interface TransactionsTableProps {
  onChange: (request: TransactionRequest) => void;
  data: TransactionResponse;
}

export const TransactionsTable = ({
  data,
  onChange,
}: TransactionsTableProps) => {
  const [startDate, setStartDate] = useState<Date | undefined>(undefined);
  const [endDate, setEndDate] = useState<Date | undefined>(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  const handlePageChange = (page: number) => {
    if (page < 1 || page > data.total_pages) return;
    setCurrentPage(page);
  };

  const getPageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5; // Maximum number of visible pages
    const halfVisible = Math.floor(maxVisiblePages / 2);

    let startPage = Math.max(1, currentPage - halfVisible);
    let endPage = Math.min(data.total_pages, currentPage + halfVisible);

    if (currentPage <= halfVisible) {
      endPage = Math.min(data.total_pages, maxVisiblePages);
    } else if (currentPage + halfVisible >= data.total_pages) {
      startPage = Math.max(1, data.total_pages - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }

    return pages;
  };

  const filterTransactions = () => {
    if (!startDate || !endDate) return;
    setCurrentPage(1); // Reset to the first page when applying filters
  };

  const { t } = useTextController();

  useEffect(() => {
    onChange({
      limit: itemsPerPage,
      page: currentPage,
      ...(startDate ? { start_date: format(startDate, 'yyyy-MM-dd') } : {}),
      ...(endDate ? { end_date: format(endDate, 'yyyy-MM-dd') } : {}),
    });
  }, [startDate, endDate, itemsPerPage, currentPage]);

  if (!data) return null;

  return (
    <div className='space-y-6'>
      <div className='flex flex-col items-start justify-between gap-4 md:flex-row md:items-center'>
        <h2 className='text-2xl font-bold'>
          {t('corporate.transactions.title')}
        </h2>

        <div className='flex w-full flex-col gap-4 md:w-auto md:flex-row'>
          <div className='grid gap-2 sm:grid-cols-2'>
            <div className='flex items-center gap-2'>
              <Label htmlFor='start-date'>
                {t('corporate.transactions.dateFrom')}
              </Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant='outline'
                    className='w-full justify-start text-left font-normal'
                  >
                    <CalendarIcon className='mr-2 h-4 w-4' />
                    {startDate
                      ? format(startDate, 'PP', { locale: ru })
                      : 'Выберите дату'}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className='w-auto p-0'>
                  <Calendar
                    mode='single'
                    selected={startDate}
                    onSelect={setStartDate}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>

            <div className='flex items-center gap-2'>
              <Label htmlFor='end-date'>
                {t('corporate.transactions.dateTo')}
              </Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant='outline'
                    className='w-full justify-start text-left font-normal'
                  >
                    <CalendarIcon className='mr-2 h-4 w-4' />
                    {endDate
                      ? format(endDate, 'PP', { locale: ru })
                      : t('corporate.transactions.selectDate')}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className='w-auto p-0'>
                  <Calendar
                    mode='single'
                    selected={endDate}
                    onSelect={setEndDate}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>
          </div>

          <Button
            className='mt-auto bg-red-600 hover:bg-red-700'
            onClick={filterTransactions}
          >
            {t('corporate.transactions.applyButton')}
          </Button>
        </div>
      </div>

      <div className='rounded-md border'>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>
                {t('corporate.transactions.tableHeaders.date')}
              </TableHead>
              <TableHead>
                {t('corporate.transactions.tableHeaders.station')}
              </TableHead>
              <TableHead>
                {t('corporate.transactions.tableHeaders.product')}
              </TableHead>
              <TableHead className='text-right'>
                {t('corporate.transactions.tableHeaders.quantity')}
              </TableHead>
              <TableHead className='text-right'>
                {t('corporate.transactions.tableHeaders.price')}
              </TableHead>
              <TableHead className='text-right'>
                {t('corporate.transactions.tableHeaders.total')}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.transactions.length > 0 ? (
              data.transactions.map((transaction) => (
                <TableRow key={transaction.id}>
                  <TableCell>
                    {format(new Date(transaction.date_create), 'dd.MM.yyyy')}
                  </TableCell>
                  <TableCell>{transaction.station}</TableCell>
                  <TableCell>{transaction.product_name}</TableCell>
                  <TableCell className='text-right'>
                    {transaction.price_real}
                  </TableCell>
                  <TableCell className='text-right'>
                    {transaction.amount} {t('corporate.currency')}
                  </TableCell>
                  <TableCell className='text-right font-medium'>
                    {transaction.sum_real} {t('corporate.currency')}
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className='py-6 text-center text-gray-500'
                >
                  {t('corporate.transactions.noTransactions')}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {data.transactions.length > 0 && (
        <div className='flex flex-col items-center justify-between gap-4 sm:flex-row'>
          <div className='text-sm text-gray-500'>
            Показано {data.transactions.length} из {data.total_records} операций
          </div>

          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious
                  onClick={() => handlePageChange(currentPage - 1)}
                  className={
                    currentPage === 1 ? 'pointer-events-none opacity-50' : ''
                  }
                />
              </PaginationItem>

              {getPageNumbers().map((page, index) => (
                <PaginationItem key={index}>
                  <PaginationLink
                    isActive={currentPage === page}
                    onClick={() => handlePageChange(page as number)}
                  >
                    {page}
                  </PaginationLink>
                </PaginationItem>
              ))}

              <PaginationItem>
                <PaginationNext
                  onClick={() => handlePageChange(currentPage + 1)}
                  className={
                    currentPage === data.total_pages
                      ? 'pointer-events-none opacity-50'
                      : ''
                  }
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>

          <div className='flex items-center gap-2'>
            <span className='text-sm text-gray-500'>Записей на странице:</span>
            <select
              className='rounded border p-1 text-sm'
              value={itemsPerPage}
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value));
                setCurrentPage(1); // Reset to first page when changing items per page
              }}
            >
              <option value={5}>5</option>
              <option value={10}>10</option>
              <option value={20}>20</option>
              <option value={50}>50</option>
            </select>
          </div>
        </div>
      )}
    </div>
  );
};
