'use client';

import React from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  CheckCircle2,
  Clock,
  Printer,
  Download,
  Building2,
  FileText,
  Calendar,
  Layers,
  ArrowDownLeft,
  X,
  CreditCard
} from 'lucide-react';
import { currency } from '@/lib/utils';

interface ReconciliationOrder {
  order_id: string;
  date: string;
  customer_name: string;
  gross_amount: number;
  admin_commission: number;
  tax: number;
  net_earning: number;
}

interface PayoutDetail {
  id: string;
  settlement_period: string;
  cycle: 'daily' | 'weekly' | 'monthly';
  generated_date: string;
  paid_date: string;
  gross_sales: number;
  commission_fee: number;
  commission_rate: number;
  tax_collected: number;
  delivery_charge_share: number;
  adjustments: number;
  net_amount: number;
  status: 'paid' | 'processing' | 'scheduled';
  payment_method: string;
  utr_number: string;
  bank_account: string;
  bank_name: string;
  order_count: number;
  orders: ReconciliationOrder[];
}

interface ReconciliationModalProps {
  isOpen: boolean;
  onClose: () => void;
  payout: PayoutDetail | null;
}

export const PayoutReconciliationModal: React.FC<ReconciliationModalProps> = ({
  isOpen,
  onClose,
  payout
}) => {
  if (!payout) return null;

  const handlePrint = () => {
    window.print();
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto p-0 border-0 bg-white rounded-2xl shadow-2xl">
        {/* Modal Header */}
        <div className="bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 p-6 text-white rounded-t-2xl relative">
          <button
            onClick={onClose}
            className="absolute top-4 right-4 text-gray-400 hover:text-white bg-gray-800/80 p-1.5 rounded-full transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
          
          <div className="flex flex-wrap items-center justify-between gap-3 pr-8">
            <div>
              <div className="flex items-center gap-2">
                <span className="px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wider rounded bg-orange-500/20 text-orange-400 border border-orange-500/30">
                  {payout.cycle} Payout
                </span>
                <span className="text-xs text-gray-400">Ref: {payout.id}</span>
              </div>
              <h2 className="text-xl font-bold mt-1 text-white">Admin Reconciliation Statement</h2>
              <p className="text-xs text-gray-300 mt-0.5 flex items-center gap-2">
                <Calendar className="w-3.5 h-3.5 text-gray-400" />
                Period: <span className="text-white font-medium">{payout.settlement_period}</span>
              </p>
            </div>

            <div className="text-right">
              <span className="text-xs text-gray-400 block">Net Paid Amount</span>
              <span className="text-2xl font-black text-green-400">
                {currency}{payout.net_amount.toFixed(2)}
              </span>
              <div className="mt-1">
                {payout.status === 'paid' ? (
                  <Badge className="bg-emerald-500/20 text-emerald-300 border-emerald-500/30 font-semibold px-2 py-0.5 text-xs inline-flex items-center gap-1">
                    <CheckCircle2 className="w-3 h-3 text-emerald-400" /> Settled & Paid
                  </Badge>
                ) : payout.status === 'processing' ? (
                  <Badge className="bg-amber-500/20 text-amber-300 border-amber-500/30 font-semibold px-2 py-0.5 text-xs inline-flex items-center gap-1">
                    <Clock className="w-3 h-3 text-amber-400" /> Processing
                  </Badge>
                ) : (
                  <Badge className="bg-blue-500/20 text-blue-300 border-blue-500/30 font-semibold px-2 py-0.5 text-xs inline-flex items-center gap-1">
                    <Clock className="w-3 h-3 text-blue-400" /> Scheduled
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="p-6 space-y-6">
          {/* Payment & Settlement Metadata Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 bg-gray-50 p-4 rounded-xl border border-gray-100 text-xs">
            <div>
              <span className="text-gray-500 block mb-1 font-medium">Payment Transfer Info</span>
              <span className="font-semibold text-gray-900 block">{payout.payment_method}</span>
              <span className="text-gray-500 text-[11px] block mt-0.5">UTR / Txn Ref: <span className="font-mono text-gray-800 font-medium">{payout.utr_number}</span></span>
            </div>
            <div>
              <span className="text-gray-500 block mb-1 font-medium">Payout Bank Account</span>
              <span className="font-semibold text-gray-900 block flex items-center gap-1.5">
                <Building2 className="w-3.5 h-3.5 text-gray-500" />
                {payout.bank_name}
              </span>
              <span className="text-gray-500 text-[11px] block mt-0.5">Acc No: <span className="font-mono text-gray-800">{payout.bank_account}</span></span>
            </div>
            <div>
              <span className="text-gray-500 block mb-1 font-medium">Settlement Execution Date</span>
              <span className="font-semibold text-gray-900 block">{payout.paid_date}</span>
              <span className="text-gray-500 text-[11px] block mt-0.5">Total Orders Covered: <span className="font-semibold text-gray-800">{payout.order_count}</span></span>
            </div>
          </div>

          {/* Financial Reconciliation Summary Breakdown */}
          <div>
            <h3 className="text-sm font-bold text-gray-900 mb-3 flex items-center gap-2">
              <Layers className="w-4 h-4 text-[var(--orange-500)]" />
              Settlement Calculation Breakdown
            </h3>
            
            <div className="rounded-xl border border-gray-200 overflow-hidden text-sm">
              <div className="divide-y divide-gray-100">
                <div className="flex justify-between items-center px-4 py-2.5 bg-white">
                  <span className="text-gray-700 font-medium flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                    Gross Customer Sales ({payout.order_count} orders)
                  </span>
                  <span className="font-semibold text-gray-900">+{currency}{payout.gross_sales.toFixed(2)}</span>
                </div>

                <div className="flex justify-between items-center px-4 py-2.5 bg-red-50/50">
                  <span className="text-red-700 font-medium flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full bg-red-500"></span>
                    Admin Platform Commission ({payout.commission_rate}%)
                  </span>
                  <span className="font-semibold text-red-600">-{currency}{payout.commission_fee.toFixed(2)}</span>
                </div>

                {payout.adjustments !== 0 && (
                  <div className="flex justify-between items-center px-4 py-2.5 bg-amber-50/50">
                    <span className="text-amber-800 font-medium flex items-center gap-2">
                      <span className="w-2 h-2 rounded-full bg-amber-500"></span>
                      Adjustments & Refund Deductions
                    </span>
                    <span className="font-semibold text-amber-700">
                      {payout.adjustments < 0 ? '-' : '+'}{currency}{Math.abs(payout.adjustments).toFixed(2)}
                    </span>
                  </div>
                )}

                <div className="flex justify-between items-center px-4 py-3 bg-gradient-to-r from-emerald-50 via-teal-50 to-emerald-50 border-t-2 border-emerald-200">
                  <div>
                    <span className="font-bold text-gray-900 block text-base">Net Amount Transferred</span>
                    <span className="text-xs text-gray-500">Gross Sales - Commission</span>
                  </div>
                  <span className="text-xl font-black text-emerald-700">
                    {currency}{payout.net_amount.toFixed(2)}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Itemized Order List in this Payout */}
          <div>
            <h3 className="text-sm font-bold text-gray-900 mb-3 flex items-center justify-between">
              <span className="flex items-center gap-2">
                <FileText className="w-4 h-4 text-[var(--orange-500)]" />
                Orders Included in Payout Batch ({payout.orders.length})
              </span>
              <span className="text-xs font-normal text-gray-500">Displaying itemized list</span>
            </h3>

            <div className="rounded-xl border border-gray-200 overflow-x-auto max-h-56">
              <table className="w-full text-xs text-left">
                <thead className="bg-gray-50 text-gray-600 sticky top-0 border-b border-gray-200 font-semibold">
                  <tr>
                    <th className="px-3.5 py-2.5">Order ID</th>
                    <th className="px-3.5 py-2.5">Date</th>
                    <th className="px-3.5 py-2.5">Customer</th>
                    <th className="px-3.5 py-2.5 text-right">Gross Total</th>
                    <th className="px-3.5 py-2.5 text-right">Admin Fee</th>
                    <th className="px-3.5 py-2.5 text-right font-bold">Net Payout</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100 font-medium">
                  {payout.orders.map((ord, idx) => (
                    <tr key={idx} className="hover:bg-gray-50 transition-colors">
                      <td className="px-3.5 py-2 text-gray-900 font-semibold">#{ord.order_id}</td>
                      <td className="px-3.5 py-2 text-gray-600">{ord.date}</td>
                      <td className="px-3.5 py-2 text-gray-800">{ord.customer_name}</td>
                      <td className="px-3.5 py-2 text-right text-gray-900">{currency}{ord.gross_amount.toFixed(2)}</td>
                      <td className="px-3.5 py-2 text-right text-red-500">-{currency}{ord.admin_commission.toFixed(2)}</td>
                      <td className="px-3.5 py-2 text-right text-emerald-600 font-bold">{currency}{ord.net_earning.toFixed(2)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Modal Action Buttons */}
          <div className="flex items-center justify-between pt-4 border-t border-gray-100">
            <div className="text-xs text-gray-400">
              Statement ID: <span className="font-mono text-gray-600">{payout.id}</span>
            </div>

            <div className="flex items-center gap-3">
              <Button
                variant="outline"
                size="sm"
                onClick={handlePrint}
                className="gap-2 text-xs font-semibold text-gray-700 hover:bg-gray-50 border-gray-300"
              >
                <Printer className="w-3.5 h-3.5" />
                Print Statement
              </Button>
              
              <Button
                size="sm"
                onClick={() => {
                  alert(`Downloading Statement ${payout.id}.pdf`);
                }}
                className="gap-2 text-xs font-semibold bg-[var(--orange-500)] hover:bg-[var(--orange-600)] text-white shadow-sm"
              >
                <Download className="w-3.5 h-3.5" />
                Download Invoice
              </Button>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
