'use client';

import React from 'react';
import { Badge } from '@/components/ui/badge';
import { ArrowDownLeft, ArrowUpRight, Clock } from 'lucide-react';
import { currency } from '@/lib/utils';
import PaginationCompo from '@/components/common/pagination';

export interface TransactionRecord {
  id?: string;
  txn_id?: string;
  date?: string;
  time?: string;
  created_at?: number;
  createdAt?: string;
  reference_id?: string;
  description?: string;
  note?: string;
  type?: string;
  source?: string;
  amount: number;
  balance_before?: number;
  balance_after: number;
  status?: string;
  order?: {
    order_database_id?: string;
    order_no?: string;
    total_amount?: number;
    cart_amount?: number;
    order_status?: string;
    payment_type?: string;
    customer_name?: string;
    items_ordered?: string;
    items?: any[];
  };
}

interface TransactionLedgerTableProps {
  transactions: TransactionRecord[];
  loading?: boolean;
  loadingMore?: boolean;
  hasMore?: boolean;
  totalCount?: number;
  onLoadMore?: () => void;
  currentPage?: number;
  itemsPerPage?: number;
  onPageChange?: (page: number) => void;
}

export const TransactionLedgerTable: React.FC<TransactionLedgerTableProps> = ({
  transactions,
  loading = false,
  loadingMore = false,
  hasMore = false,
  totalCount = 0,
  onLoadMore,
  currentPage = 1,
  itemsPerPage = 10,
  onPageChange
}) => {
  const sentinelRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (!onLoadMore || !hasMore || loading || loadingMore) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          onLoadMore();
        }
      },
      { threshold: 0.1, rootMargin: '150px' }
    );

    const currentTarget = sentinelRef.current;
    if (currentTarget) {
      observer.observe(currentTarget);
    }

    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [onLoadMore, hasMore, loading, loadingMore]);

  const formatDateTime = (item: TransactionRecord) => {
    if (item.date && item.time) {
      return { date: item.date, time: item.time };
    }
    const dateObj = item.createdAt ? new Date(item.createdAt) : item.created_at ? new Date(item.created_at) : null;
    if (dateObj && !isNaN(dateObj.getTime())) {
      return {
        date: dateObj.toISOString().split('T')[0],
        time: dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      };
    }
    return { date: 'N/A', time: '' };
  };

  const getTypeBadge = (item: TransactionRecord) => {
    const rawType = item.type || item.source || '-';
    const typeUpper = String(rawType).toUpperCase();
    const isDebit =
      typeUpper === 'DEBIT' ||
      typeUpper === 'AUTO_ADJUSTMENT' ||
      typeUpper === 'COMMISSION_DUE' ||
      (item.type !== 'CREDIT' && item.type !== 'order_credit' && item.type !== 'order_earning' && (typeUpper.includes('DEBIT') || item.amount < 0));

    if (isDebit) {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-red-50 text-red-700 border border-red-200">
          <ArrowUpRight className="w-3 h-3 text-red-600" /> {rawType}
        </span>
      );
    }

    return (
      <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
        <ArrowDownLeft className="w-3 h-3 text-emerald-600" /> {rawType}
      </span>
    );
  };

  return (
    <div className="w-full bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-left text-xs sm:text-sm">
          <thead className="bg-[#FAFAFA] text-[#828282] uppercase text-[11px] font-bold tracking-wider border-b border-gray-100">
            <tr>
              <th className="px-4 py-3.5">Txn ID</th>
              <th className="px-4 py-3.5">Date & Time</th>
              <th className="px-4 py-3.5">Reference / Order #</th>
              <th className="px-4 py-3.5">Type</th>
              <th className="px-4 py-3.5 text-right">Amount</th>
              <th className="px-4 py-3.5 text-right font-semibold">Running Balance</th>
              <th className="px-4 py-3.5 text-center">Status</th>
            </tr>
          </thead>

          <tbody className="divide-y divide-gray-100 font-medium">
            {loading ? (
              <tr>
                <td colSpan={7} className="px-4 py-12 text-center text-gray-400">
                  <div className="flex flex-col items-center justify-center space-y-2">
                    <Clock className="w-6 h-6 animate-spin text-[var(--orange-500)]" />
                    <p className="font-semibold text-gray-600 text-sm">Loading Transaction Ledger...</p>
                  </div>
                </td>
              </tr>
            ) : transactions.length > 0 ? (
              transactions.map((txn, index) => {
                const txnId = txn.txn_id || `N/A`;
                const { date, time } = formatDateTime(txn);
                const orderRef = txn.order?.order_no || txn.reference_id;
                const isCredit = txn.type === 'CREDIT' || txn.type === 'order_credit' || (txn.amount > 0 && txn.type !== 'DEBIT');

                return (
                  <tr key={txnId} className="hover:bg-gray-50/80 transition-colors">
                    <td className="px-4 py-3.5 font-mono text-xs font-semibold text-gray-900">
                      {txnId}
                    </td>
                    <td className="px-4 py-3.5 text-gray-600 whitespace-nowrap text-xs">
                      <div>{date}</div>
                      {time && <div className="text-[11px] text-gray-400">{time}</div>}
                    </td>
                    <td className="px-4 py-3.5 font-mono text-xs text-gray-800">
                      {orderRef ? `#${orderRef}` : '-'}
                    </td>
                    <td className="px-4 py-3.5 whitespace-nowrap">
                      {getTypeBadge(txn)}
                    </td>
                    <td className="px-4 py-3.5 text-right whitespace-nowrap font-bold">
                      {isCredit ? (
                        <span className="text-emerald-600">
                          +{currency}{Math.abs(txn.amount).toFixed(2)}
                        </span>
                      ) : (
                        <span className="text-red-500">
                          -{currency}{Math.abs(txn.amount).toFixed(2)}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3.5 text-right whitespace-nowrap font-bold text-gray-900">
                      {currency}{(txn.balance_after ?? 0).toFixed(2)}
                    </td>
                    <td className="px-4 py-3.5 text-center whitespace-nowrap">
                      <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 text-[11px]">
                        {txn.status || 'Completed'}
                      </Badge>
                    </td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan={7} className="px-4 py-8 text-center text-gray-400">
                  No transaction records found
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination Footer */}
      {!loading && transactions.length > 0 && (
        <div className="p-4 border-t border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-3 bg-white">
          <div className="text-xs text-gray-500 font-medium">
            Showing <span className="font-semibold text-gray-800">{((currentPage - 1) * itemsPerPage) + 1}</span> to{' '}
            <span className="font-semibold text-gray-800">{Math.min(currentPage * itemsPerPage, totalCount || transactions.length)}</span>{' '}
            {totalCount > 0 ? (
              <>
                of <span className="font-semibold text-gray-800">{totalCount}</span> entries
              </>
            ) : (
              'transactions'
            )}
          </div>

          {onPageChange && (
            <PaginationCompo
              totalDataCount={totalCount || transactions.length}
              currentPage={currentPage}
              itemsPerPage={itemsPerPage}
              onPageChange={onPageChange}
            />
          )}
        </div>
      )}
    </div>
  );
};
