"use client";

import React, { useState, useEffect } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import { currency } from '@/lib/utils';
import { PayoutsTable } from '@/components/wallet/PayoutsTable';
import { TransactionLedgerTable } from '@/components/wallet/TransactionLedgerTable';
import { BankDetailsCard } from '@/components/wallet/BankDetailsCard';
import { useGlobalContext } from '@/context/Provider';
import apis from '@/utils/apis';
import { toast } from 'sonner';
import {
  Clock,
  Calendar,
  Layers,
  Search,
  ArrowUpRight,
  ArrowDownLeft,
  Loader2,
  AlertCircle,
  Banknote
} from 'lucide-react';

const WalletPageContent = () => {
  const { userInfo } = useGlobalContext();
  const [activeTab, setActiveTab] = useState<'payouts' | 'ledger' | 'settings'>('payouts');
  const [cycleFilter, setCycleFilter] = useState<'all' | 'daily' | 'weekly' | 'monthly'>('all');
  const [adminFrequency, setAdminFrequency] = useState<'monthly' | 'weekly' | 'daily'>('monthly');
  const [searchQuery, setSearchQuery] = useState('');

  const [payoutsData, setPayoutsData] = useState<any[]>([]);
  const [summaryStats, setSummaryStats] = useState<any>(null);
  const [loadingPayouts, setLoadingPayouts] = useState<boolean>(true);

  const [ledgerData, setLedgerData] = useState<any[]>([]);
  const [loadingLedger, setLoadingLedger] = useState<boolean>(true);
  const [ledgerPage, setLedgerPage] = useState<number>(1);
  const [ledgerTotalCount, setLedgerTotalCount] = useState<number>(0);
  const ledgerItemsPerPage = 10;

  const [payoutSummary, setPayoutSummary] = useState<any>(null);
  const [withdrawLoading, setWithdrawLoading] = useState<boolean>(false);

  const fetchPayoutTable = async (id: string, search = '') => {
    try {
      setLoadingPayouts(true);
      const params: any = { page: 1, limit: 20 };
      if (search) params.search = search;
      const res = await apis.Bank.getPayoutTable(id, params);
      if (res?.data) {
        setPayoutsData(res.data);
      }
      if (res?.summary_stats) {
        setSummaryStats(res.summary_stats);
      }
    } catch (error) {
      console.error('Error fetching payout table:', error);
    } finally {
      setLoadingPayouts(false);
    }
  };

  const fetchTransactionLedger = async (id: string, page = 1) => {
    try {
      setLoadingLedger(true);
      const res = await apis.Bank.getTransactionLedger(id, { page, limit: ledgerItemsPerPage });
      if (res?.data) {
        setLedgerData(res.data);
      } else if (Array.isArray(res)) {
        setLedgerData(res);
      }
      const count = res?.pagination?.total ?? res?.count ?? res?.total ?? res?.totalCount ?? (Array.isArray(res) ? res.length : (res?.data?.length || 0));
      setLedgerTotalCount(count);
    } catch (error) {
      console.error('Error fetching transaction ledger:', error);
    } finally {
      setLoadingLedger(false);
    }
  };

  const handleLedgerPageChange = (newPage: number) => {
    setLedgerPage(newPage);
    const vendorId = userInfo?.restaurant_id?._id || userInfo?._id;
    if (vendorId) {
      fetchTransactionLedger(vendorId, newPage);
    }
  };

  const fetchPayoutSummary = async (id: string) => {
    try {
      const res = await apis.Bank.getPayoutSummary(id);
      if (res?.data) {
        setPayoutSummary(res.data);
      } else if (res) {
        setPayoutSummary(res);
      }
    } catch (error) {
      console.error('Error fetching payout summary:', error);
    }
  };

  useEffect(() => {
    const vendorId = userInfo?.restaurant_id?._id || userInfo?._id;
    if (vendorId) {
      fetchPayoutTable(vendorId, searchQuery);
      fetchTransactionLedger(vendorId, ledgerPage);
      fetchPayoutSummary(vendorId);
    } else {
      setLoadingPayouts(false);
      setLoadingLedger(false);
    }
  }, [userInfo?.restaurant_id?._id, userInfo?._id, searchQuery]);

  const totalPaidDisplay = summaryStats?.total_net_paid_formatted
    ? summaryStats.total_net_paid_formatted
    : summaryStats?.total_net_paid !== undefined
      ? `${currency}${summaryStats.total_net_paid.toFixed(2)}`
      : `$0.00`;

  const currentPayoutsList = payoutsData;

  const card1Title = payoutSummary?.summary_cards?.total_paid?.title || 'N/A';
  const card1Amount = payoutSummary?.summary_cards?.total_paid?.amount_formatted || payoutSummary?.total_paid_balances_formatted || totalPaidDisplay;
  const card1Subtext = payoutSummary?.summary_cards?.total_paid?.subtext || payoutSummary?.settled_to_date_description || 'N/A';

  const card2Title = payoutSummary?.summary_cards?.pending_balances?.title || 'N/A';
  const card2Amount = payoutSummary?.summary_cards?.pending_balances?.amount_formatted || payoutSummary?.pending_balances_formatted || 'N/A';
  const card2Subtext = payoutSummary?.summary_cards?.pending_balances?.subtext || payoutSummary?.pending_description || 'N/A';

  const codDueAmount = payoutSummary?.cod_due_amount;
  const cardCodAmount =
    codDueAmount !== undefined && codDueAmount !== null && !isNaN(Number(codDueAmount))
      ? `${currency}${Number(codDueAmount).toFixed(2)}`
      : typeof codDueAmount === 'string'
        ? codDueAmount
        : `${currency}0.00`;

  const isLastWithdrawReqPending = Boolean(payoutSummary?.is_last_withdraw_req_pending);
  const lastWithdrawRejectReason = payoutSummary?.last_withdraw_reject_reason;

  const getPendingAmountNumeric = () => {
    if (typeof payoutSummary?.summary_cards?.pending_balances?.amount === 'number') {
      return payoutSummary.summary_cards.pending_balances.amount;
    }
    if (typeof payoutSummary?.pending_balances === 'number') {
      return payoutSummary.pending_balances;
    }
    if (summaryStats?.pending_balances !== undefined && typeof summaryStats.pending_balances === 'number') {
      return summaryStats.pending_balances;
    }
    const cleanStr = (card2Amount || '').replace(/[^0-9.-]+/g, '');
    const parsed = parseFloat(cleanStr);
    return isNaN(parsed) ? 0 : parsed;
  };

  const pendingAmountNumeric = getPendingAmountNumeric();

  const handleWithdraw = async () => {
    const vendorId = userInfo?.restaurant_id?._id || userInfo?._id;
    if (pendingAmountNumeric <= 10) {
      toast.error('Withdrawal amount must be more than 10');
      return;
    }
    try {
      setWithdrawLoading(true);
      const res = await apis.Withdraw.request({
        restaurant_id: vendorId,
        amount: pendingAmountNumeric,
      });
      toast.success(res?.message || 'Withdrawal request submitted successfully!');
      if (vendorId) {
        fetchPayoutTable(vendorId, searchQuery);
        fetchTransactionLedger(vendorId);
        fetchPayoutSummary(vendorId);
      }
    } catch (error: any) {
      console.error('Error requesting withdraw:', error);
      toast.error(error?.response?.body?.message || error?.message || 'Failed to submit withdrawal request');
    } finally {
      setWithdrawLoading(false);
    }
  };

  const card3Title = payoutSummary?.summary_cards?.payout_frequency?.title || 'N/A';
  const card3Amount = payoutSummary?.summary_cards?.payout_frequency?.cycle || payoutSummary?.payout_frequency || 'N/A';
  const card3Subtext = payoutSummary?.summary_cards?.payout_frequency?.subtext || payoutSummary?.payout_frequency_description || 'N/A';

  const nextPayoutStr = payoutSummary?.schedule_card?.next_payout || payoutSummary?.next_payout_date_formatted || 'N/A';
  const activeScheduleStr = payoutSummary?.schedule_card?.active_schedule || payoutSummary?.payout_schedule_label || 'N/A';

  return (
    <div className="w-full min-h-full bg-gray-100 p-4 md:p-6 pb-20 space-y-4">
      <div className="bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 rounded-2xl p-6 text-white shadow-sm flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-[var(--orange-500)] text-white uppercase tracking-wider">
              Vendor Wallet & Payouts
            </span>
            <span className="text-xs text-gray-400">Admin Settlement Portal</span>
          </div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Payout & Wallet Overview</h1>
          <p className="text-xs text-gray-300 mt-1 max-w-xl">
            View total paid balances, pending settlements, and payouts generated by Admin. Admin sets settlement schedules (Daily, Weekly, or Monthly).
          </p>
        </div>

        {/* Active Schedule Selector / Info Pill */}
        <div className="bg-gray-800/90 border border-gray-700/80 rounded-xl p-3 text-xs min-w-[260px]">
          <div className="text-gray-400 mb-1 font-medium flex items-center justify-between">
            <span>Admin Payout Schedule</span>
            <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
          </div>
          <div className="flex items-center gap-2">
            <div className="bg-gray-900 text-white font-bold px-3 py-1.5 rounded-lg border border-gray-600 text-xs">
              {activeScheduleStr}
            </div>
          </div>
          <div className="text-[11px] text-gray-400 mt-2 flex items-center gap-1">
            <Calendar className="w-3.5 h-3.5 text-gray-300" />
            Next Payout: <span className="font-semibold text-white">{nextPayoutStr}</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Total Paid Balances Card */}
        <div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
              {card1Title}
            </span>
            <div className="w-9 h-9 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold">
              <ArrowUpRight className="w-5 h-5" />
            </div>
          </div>
          <div className="mt-3">
            <span className="text-2xl font-black text-gray-900">
              {card1Amount}
            </span>
            <span className="text-xs font-medium text-gray-500 block mt-1">
              {card1Subtext}
            </span>
          </div>
        </div>

        {/* Pending Balances Card */}
        <div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow">
          <div>
            <div className="flex items-center justify-between">
              <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
                {card2Title}
              </span>
              <div className="w-9 h-9 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center font-bold">
                <Clock className="w-5 h-5" />
              </div>
            </div>
            <div className="mt-3 flex items-end justify-between gap-2">
              <div>
                <span className="text-2xl font-black text-gray-900">
                  {card2Amount}
                </span>
                <span className="text-xs font-medium text-amber-600 block mt-1">
                  {card2Subtext}
                </span>
              </div>
              {isLastWithdrawReqPending ? (
                <div className="bg-amber-50 border border-amber-200 text-amber-700 text-xs font-bold px-3 py-2 rounded-lg flex items-center gap-1.5 shrink-0 shadow-sm">
                  <Clock className="w-3.5 h-3.5 text-amber-600 animate-pulse" />
                  <span>Request Sent</span>
                </div>
              ) : (
                pendingAmountNumeric > 10 && (
                  <button
                    type="button"
                    onClick={handleWithdraw}
                    disabled={withdrawLoading}
                    className="bg-orange-500 hover:bg-orange-600 active:bg-orange-700 text-white text-xs font-bold px-3.5 py-2 rounded-lg shadow-sm flex items-center gap-1.5 shrink-0 transition-all hover:scale-[1.03] active:scale-95 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {withdrawLoading ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 animate-spin text-white" />
                        <span className="text-white font-bold">Processing...</span>
                      </>
                    ) : (
                      <>
                        <ArrowDownLeft className="w-3.5 h-3.5 text-white" />
                        <span className="text-white font-bold">Withdraw</span>
                      </>
                    )}
                  </button>
                )
              )}
            </div>
          </div>

          {lastWithdrawRejectReason && String(lastWithdrawRejectReason).trim() !== '' && (
            <div className="mt-3 pt-2.5 border-t border-gray-100 flex items-start gap-2 text-xs text-red-600 bg-red-50/80 p-2.5 rounded-lg border border-red-100">
              <AlertCircle className="w-4 h-4 text-red-500 shrink-0 mt-0.5" />
              <div className="flex-1">
                <span className="font-bold text-red-700">Rejection Reason: </span>
                <span className="text-red-600 font-medium">{lastWithdrawRejectReason}</span>
              </div>
            </div>
          )}
        </div>

        {/* COD Due Amount Card */}
        <div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
              COD DUE AMOUNT
            </span>
            <div className="w-9 h-9 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center font-bold">
              <Banknote className="w-5 h-5" />
            </div>
          </div>
          <div className="mt-3">
            <span className="text-2xl font-black text-gray-900">
              {cardCodAmount}
            </span>
          </div>
        </div>

        {/* Active Payout Cycle Info Card */}
        <div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
              {card3Title}
            </span>
            <div className="w-9 h-9 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center font-bold">
              <Layers className="w-5 h-5" />
            </div>
          </div>
          <div className="mt-3">
            <span className="text-2xl font-black text-gray-900">
              {card3Amount}
            </span>
            <span className="text-xs font-medium text-blue-600 block mt-1">
              {card3Subtext}
            </span>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100 flex flex-col overflow-hidden">
        {/* Navigation Tabs Header */}
        <div className="p-4 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-2 overflow-x-auto pb-1 md:pb-0">
            <button
              onClick={() => setActiveTab('payouts')}
              className={`px-4 py-2 text-xs font-bold rounded-lg transition-colors whitespace-nowrap ${activeTab === 'payouts'
                ? 'bg-gray-900 text-white shadow-sm'
                : 'text-gray-600 hover:bg-gray-100'
                }`}
            >
              Payout Settlements ({currentPayoutsList.length})
            </button>

            <button
              onClick={() => setActiveTab('ledger')}
              className={`px-4 py-2 text-xs font-bold rounded-lg transition-colors whitespace-nowrap ${activeTab === 'ledger'
                ? 'bg-gray-900 text-white shadow-sm'
                : 'text-gray-600 hover:bg-gray-100'
                }`}
            >
              Transaction Ledger
            </button>

            <button
              onClick={() => setActiveTab('settings')}
              className={`px-4 py-2 text-xs font-bold rounded-lg transition-colors whitespace-nowrap ${activeTab === 'settings'
                ? 'bg-gray-900 text-white shadow-sm'
                : 'text-gray-600 hover:bg-gray-100'
                }`}
            >
              Bank & Payout Details
            </button>
          </div>

          {/* Controls bar when Payout Settlements tab is active */}
          {activeTab === 'payouts' && (
            <div className="flex flex-wrap items-center gap-2">

              {/* Search Box */}
              <div className="relative">
                <Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-2.5" />
                <input
                  type="text"
                  placeholder="Search Payout ID..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 pr-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-xs focus:outline-none focus:border-[var(--orange-500)] text-gray-900 placeholder-gray-400 w-44 sm:w-52"
                />
              </div>
            </div>
          )}
        </div>

        {/* Tab Body Contents */}
        <div className="p-4">
          {activeTab === 'payouts' && (
            <PayoutsTable
              payouts={currentPayoutsList}
              selectedCycleFilter={cycleFilter}
              loading={loadingPayouts}
            />
          )}

          {activeTab === 'ledger' && (
            <TransactionLedgerTable
              transactions={ledgerData}
              loading={loadingLedger}
              currentPage={ledgerPage}
              itemsPerPage={ledgerItemsPerPage}
              totalCount={ledgerTotalCount}
              onPageChange={handleLedgerPageChange}
            />
          )}

          {activeTab === 'settings' && (
            <BankDetailsCard
              payoutCycle={payoutSummary?.payout_frequency_type || adminFrequency}
              nextPayoutDate={payoutSummary?.schedule_card?.next_payout_date || payoutSummary?.next_payout_date || ''}
              payoutSummary={payoutSummary}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default function WalletPage() {
  return (
    <DashboardLayout>
      <WalletPageContent />
    </DashboardLayout>
  );
}
