import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import LayoutAuthenticated from '../layouts/Authenticated';
import CardBox from '../components/CardBox';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import FormField from '../components/FormField';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';

const FinancialReportsPage = () => {
  const router = useRouter();
  const { tab } = router.query;
  const [activeTab, setActiveTab] = useState('profit-loss');

  useEffect(() => {
    if (tab) {
      setActiveTab(tab as string);
    }
  }, [tab]);

  const { currentUser } = useAppSelector((state) => state.auth);
  const organizationName = currentUser?.organization?.name || 'SmartHisab';

  const tabs = [
    { id: 'profit-loss', label: 'Profit & Loss', icon: icon.mdiChartTimelineVariant },
    { id: 'balance-sheet', label: 'Balance Sheet', icon: icon.mdiScaleBalance },
    { id: 'cash-flow', label: 'Cash Flow', icon: icon.mdiCashMultiple },
    { id: 'trial-balance', label: 'Trial Balance', icon: icon.mdiBookOpenVariant },
    { id: 'income-statement', label: 'Income Statement', icon: icon.mdiTrendingUp },
    { id: 'expense-report', label: 'Expense Report', icon: icon.mdiTrendingDown },
    { id: 'tax-compliance', label: 'Tax Compliance', icon: icon.mdiFileCheckOutline },
    { id: 'sales-declaration', label: 'Sales Declaration', icon: icon.mdiCartOutline },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('Financial Reports')}</title>
      </Head>
      <SectionMain>
        <div className="flex flex-col md:flex-row md:items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-extrabold text-slate-900 mb-1">Financial Reports</h1>
            <p className="text-slate-500 font-medium text-sm">{organizationName}</p>
          </div>
          <div className="flex flex-wrap gap-3 mt-4 md:mt-0">
            <BaseButton
              label="Submit Declaration"
              color="success"
              icon={icon.mdiSend}
              className="shadow-sm"
              onClick={() => console.log('Submit Declaration clicked')}
            />
            <BaseButton
              label="Export CSV"
              color="info"
              icon={icon.mdiDownload}
              className="shadow-sm"
              onClick={() => console.log('Export CSV clicked')}
            />
            <BaseButton
              label="Print"
              color="whiteDark"
              outline
              icon={icon.mdiPrinter}
              className="bg-white"
              onClick={() => console.log('Print clicked')}
            />
          </div>
        </div>

        <CardBox className="mb-8 border-slate-200 shadow-sm overflow-visible">
          <div className="p-1">
            <h3 className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] mb-6 px-1">Report Filters</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
              <FormField label="Merchant">
                <div className="relative">
                  <select className="w-full h-12 pl-4 pr-10 border border-slate-200 rounded-xl bg-slate-50/50 focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:outline-none transition-all appearance-none font-medium text-slate-700">
                    <option>{organizationName}</option>
                  </select>
                  <BaseIcon path={icon.mdiChevronDown} className="absolute right-3 top-3 text-slate-400 pointer-events-none" size={20} />
                </div>
              </FormField>
              <FormField label="Start Date">
                <div className="relative">
                  <input type="date" className="w-full h-12 px-4 border border-slate-200 rounded-xl bg-slate-50/50 focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:outline-none transition-all font-medium text-slate-700" defaultValue="2026-01-31" />
                </div>
              </FormField>
              <FormField label="End Date">
                <div className="relative">
                  <input type="date" className="w-full h-12 px-4 border border-slate-200 rounded-xl bg-slate-50/50 focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:outline-none transition-all font-medium text-slate-700" defaultValue="2026-02-28" />
                </div>
              </FormField>
            </div>
          </div>
        </CardBox>

        <div className="mb-8 overflow-x-auto no-scrollbar -mx-4 px-4 md:mx-0 md:px-0">
          <div className="flex border-b border-slate-200 min-w-max">
            {tabs.map((t) => (
              <button
                key={t.id}
                onClick={() => {
                    setActiveTab(t.id);
                    router.push({ query: { ...router.query, tab: t.id } }, undefined, { shallow: true });
                }}
                className={`flex items-center px-6 py-4 text-sm font-bold transition-all border-b-2 -mb-[2px] ${
                  activeTab === t.id
                    ? 'border-blue-600 text-blue-600'
                    : 'border-transparent text-slate-400 hover:text-slate-600'
                }`}
              >
                <BaseIcon path={t.icon} size={20} className="mr-2" />
                {t.label}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <SummaryCard
            title="TOTAL INCOME"
            value="$170,200.00"
            change="32.5%"
            isUpTrend={false}
            color="success"
            icon={icon.mdiTrendingUp}
          />
          <SummaryCard
            title="TOTAL EXPENSES"
            value="$196,620.00"
            change="425.2%"
            isUpTrend={true}
            color="danger"
            icon={icon.mdiTrendingDown}
          />
          <SummaryCard
            title="NET PROFIT/LOSS"
            value="$26,420.00"
            change="112.3%"
            isUpTrend={false}
            color="danger"
            icon={icon.mdiCalculator}
          />
        </div>

        <CardBox className="mb-8 border-slate-200 shadow-sm overflow-hidden" hasComponentLayout>
          <div className="p-6 border-b border-slate-100 bg-white">
            <h2 className="text-xl font-extrabold text-slate-800">Period Comparison</h2>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-slate-50/50 text-slate-400 text-[10px] font-bold uppercase tracking-[0.15em]">
                  <th className="px-8 py-4 border-b border-slate-100">Metric</th>
                  <th className="px-8 py-4 border-b border-slate-100 text-right">Current Period</th>
                  <th className="px-8 py-4 border-b border-slate-100 text-right">Previous Period</th>
                  <th className="px-8 py-4 border-b border-slate-100 text-right">Change</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                <TableRow label="Income" current="$170,200.00" previous="$252,071.15" change="32.5%" isUpTrend={false} color="text-emerald-600" />
                <TableRow label="Expenses" current="$196,620.00" previous="$37,435.00" change="425.2%" isUpTrend={true} color="text-rose-600" />
                <TableRow label="Net Profit/Loss" current="-$26,420.00" previous="$214,636.15" change="112.3%" isUpTrend={false} color="text-rose-600" bold />
              </tbody>
            </table>
          </div>
        </CardBox>
      </SectionMain>
    </>
  );
};

const SummaryCard = ({ title, value, change, isUpTrend, color, icon: path }) => (
  <div className="bg-white border border-slate-200 rounded-[1.5rem] p-6 shadow-sm hover:shadow-md transition-shadow">
    <div className="flex justify-between items-start mb-6">
      <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${color === 'success' ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'}`}>
        <BaseIcon path={path} size={24} />
      </div>
      <div className={`flex items-center text-xs font-bold px-2 py-1 rounded-full ${isUpTrend ? (color === 'success' ? 'bg-emerald-50 text-emerald-600' : 'bg-emerald-50 text-emerald-600') : 'bg-rose-50 text-rose-600'}`}>
        <BaseIcon path={isUpTrend ? icon.mdiArrowUp : icon.mdiArrowDown} size={14} className="mr-1" />
        {change}
      </div>
    </div>
    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">{title}</p>
    <p className={`text-3xl font-extrabold tracking-tight ${color === 'success' ? 'text-emerald-600' : 'text-rose-600'}`}>{value}</p>
  </div>
);

const TableRow = ({ label, current, previous, change, isUpTrend, color, bold = false }) => (
  <tr className={`${bold ? 'bg-slate-50/30' : ''} hover:bg-slate-50/50 transition-colors`}>
    <td className={`px-8 py-5 text-sm font-semibold text-slate-700 ${bold ? 'text-base' : ''}`}>{label}</td>
    <td className={`px-8 py-5 text-sm font-bold text-right ${color} ${bold ? 'text-base' : ''}`}>{current}</td>
    <td className="px-8 py-5 text-sm font-medium text-right text-slate-500">{previous}</td>
    <td className={`px-8 py-5 text-sm font-bold text-right ${isUpTrend ? 'text-emerald-600' : 'text-rose-600'}`}>
      <div className="flex items-center justify-end">
        <BaseIcon path={isUpTrend ? icon.mdiArrowUp : icon.mdiArrowDown} size={16} className="mr-1" />
        {change}
      </div>
    </td>
  </tr>
);

FinancialReportsPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default FinancialReportsPage;
