'use client';

import { deleteCookie } from 'cookies-next';
import { Building2, LogOut, Wallet } from 'lucide-react';
import { useEffect, useState } from 'react';

import {
  useFetchCorporateTransactionsQuery,
  useFetchMyCorporateInfoQuery,
} from '@/entities/corporate/api/corporate.api';
import { CorporateTransactionRequest } from '@/entities/corporate/model/types/corporate-transactions.type';

import { useTextController } from '@/shared/language/hooks/use-text-controller';
import { formatDate } from '@/shared/lib/format-date';
import { Button } from '@/shared/shadcn-ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/shared/shadcn-ui/card';
import { TableCell, TableHead, TableRow } from '@/shared/shadcn-ui/table';

import { TransactionsTable } from '@/widgets/transactions-table';

export function CorporateDashboard() {
  const { t } = useTextController();

  const { data } = useFetchMyCorporateInfoQuery({});

  const [request, setTransactionFetchRequest] =
    useState<CorporateTransactionRequest>({
      limit: 10,
      page: 1,
    });

  const {
    data: transactionsResponse,
    refetch,
    isFetching,
  } = useFetchCorporateTransactionsQuery(request);

  useEffect(() => {
    refetch();
  }, [request]);

  return (
    <div className='flex min-h-screen flex-col px-2.5'>
      <main className='flex-1 py-10'>
        <div className='container mx-auto max-w-6xl'>
          <div className='mb-4 flex flex-col items-start gap-4 sm:mb-8 sm:flex-row sm:items-center sm:justify-between'>
            <h1 className='text-3xl font-bold'>{t('corporate.pageTitle')}</h1>
            <Button
              variant='outline'
              className='gap-2'
              onClick={() => {
                deleteCookie(`corporate__token`);
                window.location.reload();
              }}
            >
              <LogOut className='h-4 w-4' />
              {t('corporate.logoutButton')}
            </Button>
          </div>

          <div className='mb-10 grid gap-3 md:grid-cols-3 md:gap-6'>
            {/* Company Card */}
            <Card
              data-aos='zoom-in'
              data-aos-mirror='true'
              className='md:col-span-2'
            >
              <CardHeader className='pb-2'>
                <CardTitle className='flex items-center gap-2'>
                  <Building2 className='h-5 w-5 text-red-600' />
                  {t('corporate.companyCard.title')}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {!data ? (
                  <>Loading</>
                ) : (
                  <div className='grid gap-6 md:grid-cols-2'>
                    <div>
                      <div className='mb-4 space-y-1'>
                        <p className='text-sm text-gray-500'>
                          {t('corporate.companyCard.companyNameLabel')}
                        </p>
                        <p className='truncate font-medium'>
                          {data.group_name}
                        </p>
                      </div>
                      <div className='mb-4 space-y-1'>
                        <p className='text-sm text-gray-500'>
                          {t('corporate.companyCard.cardsCountLabel')}
                        </p>
                        <p className='font-medium'>{data.total_cards}</p>
                      </div>
                      <div className='space-y-1'>
                        <p className='text-sm text-gray-500'>
                          {t('corporate.companyCard.registrationDateLabel')}
                        </p>

                        <p className='font-medium'>
                          {new Date(data.created_at).toLocaleDateString(
                            'en-GB',
                          )}
                        </p>
                      </div>
                    </div>
                    <div>
                      <div className='mb-4 space-y-1'>
                        <p className='text-sm text-gray-500'>
                          {t('corporate.companyCard.fundLabel')}
                        </p>
                        <p className='font-medium'>
                          {data.fund.toLocaleString()} {t('corporate.currency')}
                        </p>
                      </div>
                      <div className='mb-4 space-y-1'>
                        <p className='text-sm text-gray-500'>
                          {t('corporate.companyCard.overdraftLabel')}
                        </p>
                        <p className='font-medium'>
                          {data.overdraft.toLocaleString()}{' '}
                          {t('corporate.currency')}
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Fund Card */}
            <Card
              data-aos='zoom-in'
              data-aos-mirror='true'
              className='bg-gradient-to-br from-red-600 to-red-800 text-white'
            >
              <CardHeader>
                <CardTitle className='flex items-center gap-2'>
                  <Wallet className='h-5 w-5' />
                  {t('corporate.fundCard.title')}
                </CardTitle>
                <CardDescription className='text-white/80'>
                  {t('corporate.fundCard.description')}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {!data ? (
                  <>Loading</>
                ) : (
                  <div className='text-center'>
                    <p className='mb-2 text-4xl font-bold'>
                      {data.fund_total?.toLocaleString()}
                    </p>
                    <p className='text-white/80'>
                      {t('corporate.fundCard.currency')}
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <TransactionsTable
            isLoading={isFetching}
            renderHeaders={() => (
              <TableRow>
                <TableHead>
                  {t('corporate.transactions.tableHeaders.date')}
                </TableHead>
                <TableHead>
                  {t('corporate.transactions.tableHeaders.card')}
                </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>
            )}
            renderRow={(transaction, index) => (
              <TableRow key={index}>
                <TableCell>
                  {formatDate(
                    new Date(transaction.date_create),
                    'dd.MM.yyyy HH:mm',
                  )}
                </TableCell>
                <TableCell>{transaction.uid}</TableCell>
                <TableCell>{transaction.station_name}</TableCell>
                <TableCell>{transaction.product_name}</TableCell>
                <TableCell className='text-right'>
                  {transaction.amount}
                </TableCell>
                <TableCell className='text-right'>
                  {transaction.price_real} {t('corporate.currency')}
                </TableCell>
                <TableCell className='text-right font-medium'>
                  {transaction.sum_real} {t('corporate.currency')}
                </TableCell>
              </TableRow>
            )}
            data={
              transactionsResponse || {
                limit: 10,
                current_page: 1,
                total_pages: 0,
                total_records: 0,
                transactions: [],
              }
            }
            onChange={setTransactionFetchRequest}
          />
        </div>
      </main>
    </div>
  );
}
