import { mdiArrowBottomLeft, mdiArrowTopRight, mdiCalendar, mdiFilterVariant, mdiPlus } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import BaseIcon from '../components/BaseIcon';
import BaseButton from '../components/BaseButton';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetchTransactions } from '../stores/transactions/transactionsSlice';
import { Pagination } from '../components/Pagination';

const TransactionsPage = () => {
  const dispatch = useAppDispatch();
  const { transactions, loading, count } = useAppSelector((state) => state.transactions);
  const [currentPage, setCurrentPage] = useState(0);
  const perPage = 10;

  useEffect(() => {
    const query = `?page=${currentPage}&limit=${perPage}`;
    dispatch(fetchTransactions({ query }));
  }, [dispatch, currentPage]);

  const onPageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Transactions')}</title>
      </Head>
      <SectionMain>
        <div className="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4">
          <div>
            <p className="text-gray-500 font-medium mb-1 text-sm">ግብይቶች</p>
            <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight mb-1">Transactions</h1>
            <p className="text-slate-500 font-medium">Manage and track all your business financial activities</p>
          </div>
          <div className="flex items-center gap-3">
            <BaseButton
              label="New Transaction"
              icon={mdiPlus}
              color="info"
              href="/transaction-entry"
              className="rounded-xl shadow-md hover:shadow-lg transition-all"
            />
          </div>
        </div>

        <CardBox className="mb-6 rounded-[1.5rem] shadow-sm border-gray-100 overflow-hidden" hasTable>
          <div className="p-6 border-b border-gray-50 flex flex-wrap items-center justify-between gap-4">
            <div className="flex flex-wrap items-center gap-4">
              <div className="relative group">
                <select className="pl-10 pr-10 py-2.5 bg-gray-50 hover:bg-gray-100 border-none rounded-xl text-sm font-bold text-slate-600 focus:ring-2 focus:ring-indigo-500 appearance-none cursor-pointer min-w-[140px] transition-colors">
                  <option>All Types</option>
                  <option>Income</option>
                  <option>Expense</option>
                </select>
                <BaseIcon path={mdiFilterVariant} size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                  <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7"></path></svg>
                </div>
              </div>
              <div className="relative group">
                <select className="pl-10 pr-10 py-2.5 bg-gray-50 hover:bg-gray-100 border-none rounded-xl text-sm font-bold text-slate-600 focus:ring-2 focus:ring-indigo-500 appearance-none cursor-pointer min-w-[160px] transition-colors">
                  <option>Last 30 days</option>
                  <option>This Month</option>
                  <option>Last Quarter</option>
                  <option>This Year</option>
                </select>
                <BaseIcon path={mdiCalendar} size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                  <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7"></path></svg>
                </div>
              </div>
            </div>
            <div className="text-xs font-bold text-slate-400 uppercase tracking-widest bg-gray-50 px-3 py-1.5 rounded-lg">
              Showing {transactions.length} of {count} entries
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-gray-50/50">
                  <th className="px-6 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">Date</th>
                  <th className="px-6 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">Description</th>
                  <th className="px-6 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">Type</th>
                  <th className="px-6 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">Status</th>
                  <th className="px-6 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest text-right">Amount</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {loading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <tr key={i} className="animate-pulse">
                      <td colSpan={5} className="px-6 py-8">
                        <div className="flex gap-4 items-center">
                          <div className="w-12 h-4 bg-gray-100 rounded"></div>
                          <div className="flex-grow h-4 bg-gray-100 rounded"></div>
                          <div className="w-20 h-4 bg-gray-100 rounded"></div>
                        </div>
                      </td>
                    </tr>
                  ))
                ) : transactions.length > 0 ? (
                  transactions.map((transaction) => (
                    <tr key={transaction.id} className="group hover:bg-indigo-50/30 transition-colors">
                      <td className="px-6 py-5 text-sm font-medium text-slate-500">
                        {new Date(transaction.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                      </td>
                      <td className="px-6 py-5">
                        <div className="text-sm font-bold text-slate-800 group-hover:text-indigo-600 transition-colors">{transaction.description}</div>
                        <div className="text-[10px] text-slate-400 uppercase font-bold tracking-tight mt-0.5">{transaction.entity?.replace('_', ' ')}</div>
                      </td>
                      <td className="px-6 py-5">
                        <div className={`inline-flex items-center px-3 py-1 rounded-full text-[10px] font-bold shadow-sm border border-opacity-10 ${
                          transaction.isIncome 
                            ? 'bg-emerald-50 text-emerald-600 border-emerald-500' 
                            : 'bg-rose-50 text-rose-600 border-rose-500'
                        }`}>
                          <BaseIcon 
                            path={transaction.isIncome ? mdiArrowTopRight : mdiArrowBottomLeft} 
                            size={14} 
                            className="mr-1.5" 
                          />
                          {transaction.type}
                        </div>
                      </td>
                      <td className="px-6 py-5">
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${
                          transaction.status === 'approved' || transaction.status === 'submitted'
                            ? 'bg-blue-50 text-blue-600'
                            : 'bg-slate-100 text-slate-500'
                        }`}>
                          {transaction.status}
                        </span>
                      </td>
                      <td className={`px-6 py-5 text-sm font-bold text-right ${
                        transaction.isIncome ? 'text-emerald-600' : 'text-rose-600'
                      }`}>
                        {transaction.isIncome ? '+' : '-'}{Number(transaction.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={5} className="px-6 py-16 text-center">
                      <div className="flex flex-col items-center">
                        <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
                          <BaseIcon path={mdiFilterVariant} size={32} className="text-slate-300" />
                        </div>
                        <p className="text-slate-400 font-bold uppercase tracking-widest text-xs">No transactions found</p>
                        <p className="text-slate-300 text-sm mt-1">Try adjusting your filters or add a new entry</p>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          <div className="p-6 border-t border-gray-50 bg-gray-50/20 flex justify-center">
            <Pagination
              currentPage={currentPage}
              numPages={Math.ceil(count / perPage) || 1}
              setCurrentPage={onPageChange}
            />
          </div>
        </CardBox>
      </SectionMain>
    </>
  );
};

TransactionsPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission="READ_TRANSACTIONS">{page}</LayoutAuthenticated>;
};

export default TransactionsPage;