'use client';

import { subMonths } from 'date-fns';
import { Building2, LogOut, Wallet } from 'lucide-react';
import { useState } from 'react';

import { useFetchMyCorporateInfoQuery } from '@/entities/corporate/api/corporate.api';

import { useTextController } from '@/shared/language/hooks/use-text-controller';
import { Button } from '@/shared/shadcn-ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/shared/shadcn-ui/card';

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

// import { CardsList } from '@/widgets/cards-list';

// Sample company data
const companyData = {
  companyName: 'ООО «ТаджикТранс»',
  numberOfCards: 12,
  fund: 25000,
  overdraft: 5000,
  totalFund: 30000,
  registrationDate: '10.03.2019',
};

// Sample transaction data
const generateTransactions = () => {
  const stations = [
    'АЗС Душанбе-Центр',
    'АЗС Душанбе-Запад',
    'АЗС Душанбе-Восток',
    'АЗС Худжанд',
    'АЗС Куляб',
  ];

  const products = [
    { name: 'ДТ', price: 8.5 },
    { name: 'АИ-92', price: 9.2 },
    { name: 'АИ-95', price: 10.5 },
    { name: 'Z-100 Power', price: 11.8 },
    { name: 'Пропан', price: 6.3 },
  ];

  const transactions = [];

  // Generate 50 random transactions over the last 6 months
  for (let i = 0; i < 50; i++) {
    const date = subMonths(new Date(), Math.random() * 6);
    const station = stations[Math.floor(Math.random() * stations.length)];
    const product = products[Math.floor(Math.random() * products.length)];
    const quantity = Math.floor(Math.random() * 40) + 10; // 10-50 liters
    const cost = product.price;
    const total = quantity * cost;

    transactions.push({
      id: i + 1,
      date,
      station,
      product: product.name,
      quantity,
      cost,
      total,
    });
  }

  // Sort by date (newest first)
  return transactions.sort((a, b) => b.date.getTime() - a.date.getTime());
};

const transactions = generateTransactions();

export function CorporateDashboard() {
  const [startDate, setStartDate] = useState<Date | undefined>(
    subMonths(new Date(), 1),
  );
  const [endDate, setEndDate] = useState<Date | undefined>(new Date());
  const [filteredTransactions, setFilteredTransactions] =
    useState(transactions);

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

    const filtered = transactions.filter((transaction) => {
      const transactionDate = new Date(transaction.date);
      return transactionDate >= startDate && transactionDate <= endDate;
    });

    setFilteredTransactions(filtered);
  };

  const { t } = useTextController();

  const { data, isLoading } = useFetchMyCorporateInfoQuery({});

  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 gap-4 items-start sm:justify-between sm:items-center sm:mb-8 sm:flex-row'>
            <h1 className='text-3xl font-bold'>{t('corporate.pageTitle')}</h1>
            <Button variant='outline' className='gap-2'>
              <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>

          {/* <CardsList totalCards={companyData.numberOfCards} /> */}

          {/* Transactions */}

          <TransactionsTable />
        </div>
      </main>
    </div>
  );
}
