'use client';

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

import { useFetchBonusTransactionsQuery } from '@/entities/bonus/api/bonus.api';

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';

export const TransactionsTable = () => {
  const [startDate, setStartDate] = useState<Date | undefined>(
    subMonths(new Date(), 1),
  );
  const [endDate, setEndDate] = useState<Date | undefined>(new Date());

  const { data, refetch } = useFetchBonusTransactionsQuery({
    limit: 100,
    page: 1,
    ...(startDate ? { start_date: format(startDate, 'yyyy-MM-dd') } : {}),
    ...(endDate ? { end_date: format(endDate, 'yyyy-MM-dd') } : {}),
  });

  // Filter transactions by date range
  const filterTransactions = () => {
    if (!startDate || !endDate) return;

    refetch();
  };

  const { t } = useTextController();

  useEffect(() => {}, [startDate, endDate]);

  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 sm:grid-cols-2 gap-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>
    </div>
  );
};
