'use client';

import React from 'react';
import { Badge } from '@/components/ui/badge';
import {
  CheckCircle2,
  Clock,
  Layers,
  FileText,
  Download,
  AlertCircle
} from 'lucide-react';
import { currency } from '@/lib/utils';

export interface PayoutRecord {
  id: string;
  payout_ref_id?: string;
  payout_date?: string;
  settlement_period: string;
  cycle?: 'daily' | 'weekly' | 'monthly' | string;
  payout_cycle?: string;
  payout_cycle_badge?: {
    label: string;
    dot_color?: string;
    color?: string;
  };
  generated_date?: string;
  paid_date?: string;
  gross_sales: number;
  gross_sales_formatted?: string;
  admin_fee?: number;
  admin_fee_formatted?: string;
  commission_fee?: number;
  commission_rate?: number;
  tax_collected?: number;
  delivery_charge_share?: number;
  adjustments?: number;
  net_amount?: number;
  net_paid?: number;
  net_paid_formatted?: string;
  status: string;
  status_label?: string;
  status_badge?: {
    label: string;
    color?: string;
  };
  payment_method: string;
  utr_number?: string;
  bank_account?: string;
  bank_name?: string;
  order_count?: number;
  orders_count?: number;
  invoice_url?: string | null;
  orders?: any[];
}

interface PayoutsTableProps {
  payouts: PayoutRecord[];
  selectedCycleFilter?: string;
  loading?: boolean;
}

export const PayoutsTable: React.FC<PayoutsTableProps> = ({
  payouts,
  selectedCycleFilter = 'all',
  loading = false
}) => {
  const getCycleBadge = (item: PayoutRecord) => {
    if (item.payout_cycle_badge) {
      const badge = item.payout_cycle_badge;
      const dotColor = badge.dot_color || (badge.color === 'purple' ? '#8b5cf6' : badge.color === 'blue' ? '#3b82f6' : '#f59e0b');
      return (
        <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-gray-50 text-gray-800 border border-gray-200">
          <span className="w-2 h-2 rounded-full" style={{ backgroundColor: dotColor }}></span>
          {badge.label}
        </span>
      );
    }

    const cycleVal = (item.payout_cycle || item.cycle || 'monthly').toLowerCase();
    switch (cycleVal) {
      case 'daily':
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-blue-50 text-blue-700 border border-blue-200">
            <span className="w-1.5 h-1.5 rounded-full bg-blue-500"></span>
            Daily
          </span>
        );
      case 'weekly':
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-purple-50 text-purple-700 border border-purple-200">
            <span className="w-1.5 h-1.5 rounded-full bg-purple-500"></span>
            Weekly
          </span>
        );
      case 'monthly':
      default:
        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 border border-amber-200">
            <span className="w-1.5 h-1.5 rounded-full bg-amber-500"></span>
            Monthly
          </span>
        );
    }
  };

  const getStatusBadge = (item: PayoutRecord) => {
    const statusKey = (item.status || '').toLowerCase();
    const label = item.status_badge?.label || item.status_label || (statusKey === 'success' || statusKey === 'paid' ? 'Paid & Settled' : statusKey === 'pending' ? 'Pending' : item.status);

    if (statusKey === 'success' || statusKey === 'paid' || item.status_badge?.color === 'green') {
      return (
        <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100 font-semibold px-2.5 py-1 text-xs inline-flex items-center gap-1">
          <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
          {label}
        </Badge>
      );
    }

    if (statusKey === 'pending' || statusKey === 'processing' || item.status_badge?.color === 'yellow') {
      return (
        <Badge className="bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100 font-semibold px-2.5 py-1 text-xs inline-flex items-center gap-1">
          <Clock className="w-3.5 h-3.5 text-amber-600 animate-spin" />
          {label}
        </Badge>
      );
    }

    if (statusKey === 'failed' || item.status_badge?.color === 'red') {
      return (
        <Badge className="bg-red-50 text-red-700 border-red-200 hover:bg-red-100 font-semibold px-2.5 py-1 text-xs inline-flex items-center gap-1">
          <AlertCircle className="w-3.5 h-3.5 text-red-600" />
          {label}
        </Badge>
      );
    }

    return (
      <Badge className="bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100 font-semibold px-2.5 py-1 text-xs inline-flex items-center gap-1">
        <Clock className="w-3.5 h-3.5 text-blue-600" />
        {label}
      </Badge>
    );
  };

  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">Payout Ref ID</th>
              <th className="px-4 py-3.5">Payout Cycle</th>
              <th className="px-4 py-3.5">Settlement Period</th>
              <th className="px-4 py-3.5 text-center">Orders</th>
              <th className="px-4 py-3.5 text-right">Gross Sales</th>
              <th className="px-4 py-3.5 text-right">Admin Fee</th>
              <th className="px-4 py-3.5 text-right font-bold text-gray-900">Net Paid</th>
              <th className="px-4 py-3.5">Payment Method</th>
              <th className="px-4 py-3.5">Status</th>
            </tr>
          </thead>

          <tbody className="divide-y divide-gray-100 font-medium">
            {loading ? (
              <tr>
                <td colSpan={9} 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 Payout Settlements...</p>
                  </div>
                </td>
              </tr>
            ) : payouts.length > 0 ? (
              payouts.map((item) => {
                const refId = item.payout_ref_id || item.id;
                const payoutDate = item.payout_date || (item.paid_date ? `Date: ${item.paid_date}` : '');
                const ordersCount = item.orders_count ?? item.order_count ?? 0;
                const grossSalesFormatted = item.gross_sales_formatted || `${currency}${(item.gross_sales || 0).toFixed(2)}`;
                const adminFeeFormatted = item.admin_fee_formatted || `-${currency}${Math.abs(item.admin_fee ?? item.commission_fee ?? 0).toFixed(2)}`;
                const netPaidFormatted = item.net_paid_formatted || `${currency}${(item.net_paid ?? item.net_amount ?? 0).toFixed(2)}`;

                return (
                  <tr
                    key={item.id}
                    className="hover:bg-gray-50/80 transition-colors"
                  >
                    <td className="px-4 py-4 whitespace-nowrap">
                      <span className="font-bold text-gray-900 font-mono text-xs block">
                        {refId}
                      </span>
                      {payoutDate && (
                        <span className="text-[11px] text-gray-400 font-normal">
                          {payoutDate}
                        </span>
                      )}
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap">
                      {getCycleBadge(item)}
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap text-gray-700 font-medium text-xs">
                      {item.settlement_period}
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap text-center text-xs">
                      <span className="inline-block bg-gray-100 text-gray-800 font-bold px-2 py-0.5 rounded-full">
                        {ordersCount}
                      </span>
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap text-right text-gray-700">
                      {grossSalesFormatted}
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap text-right text-red-500 font-semibold">
                      {adminFeeFormatted}
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap text-right">
                      <span className="text-base font-black text-emerald-600">
                        {netPaidFormatted}
                      </span>
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-semibold text-gray-800">{item.payment_method}</span>
                        {item.invoice_url && (
                          <a
                            href={item.invoice_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors"
                            title="Download Invoice PDF"
                          >
                            <Download className="w-3.5 h-3.5" />
                          </a>
                        )}
                      </div>
                    </td>

                    <td className="px-4 py-4 whitespace-nowrap">
                      {getStatusBadge(item)}
                    </td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan={9} className="px-4 py-12 text-center text-gray-400">
                  <div className="flex flex-col items-center justify-center space-y-2">
                    <Layers className="w-8 h-8 text-gray-300" />
                    <p className="font-semibold text-gray-600 text-sm">No Payout Records Found</p>
                    <p className="text-xs text-gray-400">
                      No payout settlements available.
                    </p>
                  </div>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};
