/**
 * RefundList Component
 * Paginated list of refund requests with status tracking
 * Epic: OQI-005 Pagos y Stripe
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  RotateCcw,
  Search,
  Filter,
  ChevronDown,
  ChevronUp,
  ChevronLeft,
  ChevronRight,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Loader2,
  ExternalLink,
  Download,
  Calendar,
  CreditCard,
  DollarSign,
  MessageSquare,
} from 'lucide-react';

// Types
export type RefundStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'canceled';

export interface Refund {
  id: string;
  subscriptionId: string;
  subscriptionName: string;
  invoiceId?: string;
  amount: number;
  currency: string;
  reason: string;
  reasonDetails?: string;
  status: RefundStatus;
  refundMethod: 'original' | 'wallet';
  requestedAt: string;
  processedAt?: string;
  failureReason?: string;
  transactionId?: string;
}

export interface RefundListProps {
  refunds: Refund[];
  totalCount: number;
  currentPage: number;
  pageSize: number;
  onPageChange?: (page: number) => void;
  onViewInvoice?: (invoiceId: string) => void;
  onRetryRefund?: (refundId: string) => void;
  onCancelRefund?: (refundId: string) => void;
  onExport?: () => void;
  isLoading?: boolean;
  showFilters?: boolean;
}

// Status configurations
const STATUS_CONFIG: Record<RefundStatus, { label: string; color: string; bgColor: string; icon: React.ElementType }> = {
  pending: {
    label: 'Pending',
    color: 'text-amber-400',
    bgColor: 'bg-amber-900/50',
    icon: Clock,
  },
  processing: {
    label: 'Processing',
    color: 'text-blue-400',
    bgColor: 'bg-blue-900/50',
    icon: Loader2,
  },
  completed: {
    label: 'Completed',
    color: 'text-emerald-400',
    bgColor: 'bg-emerald-900/50',
    icon: CheckCircle,
  },
  failed: {
    label: 'Failed',
    color: 'text-red-400',
    bgColor: 'bg-red-900/50',
    icon: XCircle,
  },
  canceled: {
    label: 'Canceled',
    color: 'text-slate-400',
    bgColor: 'bg-slate-800',
    icon: XCircle,
  },
};

// Currency formatter
const formatCurrency = (amount: number, currency: string = 'USD') => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency,
    minimumFractionDigits: 2,
  }).format(amount);
};

// Date formatter (accepts Date or string)
function formatDate(date: Date | string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  return new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  }).format(d);
}

// Time formatter (accepts Date or string)
function formatTime(date: Date | string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  return new Intl.DateTimeFormat('en-US', {
    hour: '2-digit',
    minute: '2-digit',
  }).format(d);
}

// Status badge component
const StatusBadge: React.FC<{ status: RefundStatus }> = ({ status }) => {
  const config = STATUS_CONFIG[status];
  const Icon = config.icon;

  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${config.bgColor} ${config.color}`}>
      <Icon className={`w-3 h-3 ${status === 'processing' ? 'animate-spin' : ''}`} />
      {config.label}
    </span>
  );
};

const RefundList: React.FC<RefundListProps> = ({
  refunds,
  totalCount,
  currentPage,
  pageSize,
  onPageChange,
  onViewInvoice,
  onRetryRefund,
  onCancelRefund,
  onExport,
  isLoading = false,
  showFilters = true,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<RefundStatus | 'all'>('all');
  const [expandedRefundId, setExpandedRefundId] = useState<string | null>(null);
  const [showStatusDropdown, setShowStatusDropdown] = useState(false);

  // Calculate pagination
  const totalPages = useMemo(() => Math.ceil(totalCount / pageSize), [totalCount, pageSize]);
  const startIndex = (currentPage - 1) * pageSize + 1;
  const endIndex = Math.min(currentPage * pageSize, totalCount);

  // Filter refunds locally (for demo - in production, filtering would be server-side)
  const filteredRefunds = useMemo(() => {
    return refunds.filter((refund) => {
      // Status filter
      if (statusFilter !== 'all' && refund.status !== statusFilter) return false;

      // Search filter
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        return (
          refund.id.toLowerCase().includes(query) ||
          refund.subscriptionName.toLowerCase().includes(query) ||
          refund.reason.toLowerCase().includes(query)
        );
      }

      return true;
    });
  }, [refunds, statusFilter, searchQuery]);

  // Toggle row expansion
  const toggleExpand = useCallback((refundId: string) => {
    setExpandedRefundId((prev) => (prev === refundId ? null : refundId));
  }, []);

  // Render filters
  const renderFilters = () => (
    <div className="flex flex-wrap items-center gap-4 mb-6">
      {/* Search */}
      <div className="flex-1 min-w-[200px]">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search refunds..."
            className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-10 pr-4 py-2 text-white text-sm focus:border-blue-500 focus:outline-none"
          />
        </div>
      </div>

      {/* Status Filter */}
      <div className="relative">
        <button
          onClick={() => setShowStatusDropdown(!showStatusDropdown)}
          className="flex items-center gap-2 px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white hover:border-slate-600 transition-colors"
        >
          <Filter className="w-4 h-4" />
          Status: {statusFilter === 'all' ? 'All' : STATUS_CONFIG[statusFilter].label}
          <ChevronDown className="w-4 h-4" />
        </button>

        {showStatusDropdown && (
          <div className="absolute z-10 w-48 mt-2 bg-slate-800 border border-slate-700 rounded-lg shadow-xl overflow-hidden">
            <button
              onClick={() => {
                setStatusFilter('all');
                setShowStatusDropdown(false);
              }}
              className={`w-full px-4 py-2 text-left text-sm hover:bg-slate-700 ${
                statusFilter === 'all' ? 'text-blue-400' : 'text-white'
              }`}
            >
              All Statuses
            </button>
            {Object.entries(STATUS_CONFIG).map(([status, config]) => (
              <button
                key={status}
                onClick={() => {
                  setStatusFilter(status as RefundStatus);
                  setShowStatusDropdown(false);
                }}
                className={`w-full px-4 py-2 text-left text-sm hover:bg-slate-700 flex items-center gap-2 ${
                  statusFilter === status ? 'text-blue-400' : 'text-white'
                }`}
              >
                <config.icon className={`w-4 h-4 ${config.color}`} />
                {config.label}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Export Button */}
      {onExport && (
        <button
          onClick={onExport}
          className="flex items-center gap-2 px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white hover:border-slate-600 transition-colors"
        >
          <Download className="w-4 h-4" />
          Export
        </button>
      )}
    </div>
  );

  // Render empty state
  const renderEmptyState = () => (
    <div className="text-center py-12">
      <RotateCcw className="w-12 h-12 text-slate-600 mx-auto mb-4" />
      <h3 className="text-white font-medium mb-2">No Refunds Found</h3>
      <p className="text-slate-400 text-sm">
        {searchQuery || statusFilter !== 'all'
          ? 'Try adjusting your filters'
          : "You haven't requested any refunds yet"}
      </p>
    </div>
  );

  // Render loading state
  const renderLoadingState = () => (
    <div className="flex items-center justify-center py-12">
      <Loader2 className="w-8 h-8 text-blue-400 animate-spin" />
    </div>
  );

  // Render refund row
  const renderRefundRow = (refund: Refund) => {
    const isExpanded = expandedRefundId === refund.id;

    return (
      <div key={refund.id} className="border-b border-slate-800 last:border-0">
        {/* Main Row */}
        <div
          className="flex items-center gap-4 p-4 hover:bg-slate-800/50 cursor-pointer transition-colors"
          onClick={() => toggleExpand(refund.id)}
        >
          {/* Expand Toggle */}
          <button className="text-slate-500">
            {isExpanded ? (
              <ChevronUp className="w-4 h-4" />
            ) : (
              <ChevronDown className="w-4 h-4" />
            )}
          </button>

          {/* Date */}
          <div className="w-24 text-slate-400 text-sm">
            {formatDate(refund.requestedAt)}
          </div>

          {/* Subscription */}
          <div className="flex-1 min-w-0">
            <p className="text-white font-medium truncate">{refund.subscriptionName}</p>
            <p className="text-slate-500 text-xs truncate">{refund.reason}</p>
          </div>

          {/* Amount */}
          <div className="w-28 text-right">
            <p className="text-white font-medium">
              {formatCurrency(refund.amount, refund.currency)}
            </p>
            <p className="text-slate-500 text-xs capitalize">{refund.refundMethod}</p>
          </div>

          {/* Status */}
          <div className="w-28">
            <StatusBadge status={refund.status} />
          </div>
        </div>

        {/* Expanded Details */}
        {isExpanded && (
          <div className="px-4 pb-4 ml-8 space-y-4">
            <div className="grid grid-cols-2 gap-4 p-4 bg-slate-800/50 rounded-lg">
              {/* Reference ID */}
              <div>
                <span className="text-slate-500 text-xs block">Reference ID</span>
                <span className="text-white font-mono text-sm">{refund.id}</span>
              </div>

              {/* Requested At */}
              <div>
                <span className="text-slate-500 text-xs block">Requested</span>
                <span className="text-white text-sm">
                  {formatDate(refund.requestedAt)} at {formatTime(refund.requestedAt)}
                </span>
              </div>

              {/* Processed At */}
              {refund.processedAt && (
                <div>
                  <span className="text-slate-500 text-xs block">Processed</span>
                  <span className="text-white text-sm">
                    {formatDate(refund.processedAt)} at {formatTime(refund.processedAt)}
                  </span>
                </div>
              )}

              {/* Transaction ID */}
              {refund.transactionId && (
                <div>
                  <span className="text-slate-500 text-xs block">Transaction ID</span>
                  <span className="text-white font-mono text-sm">{refund.transactionId}</span>
                </div>
              )}

              {/* Reason Details */}
              {refund.reasonDetails && (
                <div className="col-span-2">
                  <span className="text-slate-500 text-xs block mb-1">Details</span>
                  <p className="text-slate-300 text-sm">{refund.reasonDetails}</p>
                </div>
              )}

              {/* Failure Reason */}
              {refund.status === 'failed' && refund.failureReason && (
                <div className="col-span-2">
                  <div className="flex items-start gap-2 p-3 bg-red-900/20 rounded-lg border border-red-800/50">
                    <AlertCircle className="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" />
                    <div>
                      <span className="text-red-400 text-sm font-medium block">Failure Reason</span>
                      <span className="text-slate-400 text-sm">{refund.failureReason}</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Actions */}
            <div className="flex items-center gap-3">
              {refund.invoiceId && onViewInvoice && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onViewInvoice(refund.invoiceId!);
                  }}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm text-blue-400 hover:text-blue-300 transition-colors"
                >
                  <ExternalLink className="w-4 h-4" />
                  View Invoice
                </button>
              )}

              {refund.status === 'failed' && onRetryRefund && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onRetryRefund(refund.id);
                  }}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm text-amber-400 hover:text-amber-300 transition-colors"
                >
                  <RotateCcw className="w-4 h-4" />
                  Retry Request
                </button>
              )}

              {refund.status === 'pending' && onCancelRefund && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onCancelRefund(refund.id);
                  }}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm text-red-400 hover:text-red-300 transition-colors"
                >
                  <XCircle className="w-4 h-4" />
                  Cancel Request
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  // Render pagination
  const renderPagination = () => {
    if (totalPages <= 1) return null;

    return (
      <div className="flex items-center justify-between px-4 py-3 border-t border-slate-800">
        <div className="text-slate-400 text-sm">
          Showing {startIndex}-{endIndex} of {totalCount} refunds
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => onPageChange?.(currentPage - 1)}
            disabled={currentPage === 1}
            className="p-2 text-slate-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>

          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let page: number;
            if (totalPages <= 5) {
              page = i + 1;
            } else if (currentPage <= 3) {
              page = i + 1;
            } else if (currentPage >= totalPages - 2) {
              page = totalPages - 4 + i;
            } else {
              page = currentPage - 2 + i;
            }

            return (
              <button
                key={page}
                onClick={() => onPageChange?.(page)}
                className={`w-8 h-8 rounded-lg text-sm transition-colors ${
                  currentPage === page
                    ? 'bg-blue-600 text-white'
                    : 'text-slate-400 hover:text-white hover:bg-slate-800'
                }`}
              >
                {page}
              </button>
            );
          })}

          <button
            onClick={() => onPageChange?.(currentPage + 1)}
            disabled={currentPage === totalPages}
            className="p-2 text-slate-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>
      </div>
    );
  };

  return (
    <div className="bg-slate-900 rounded-xl border border-slate-800">
      {/* Header */}
      <div className="p-6 border-b border-slate-800">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <RotateCcw className="w-6 h-6 text-blue-400" />
            <div>
              <h2 className="text-white text-lg font-semibold">Refund History</h2>
              <p className="text-slate-400 text-sm">{totalCount} total refund requests</p>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      {showFilters && <div className="p-6 border-b border-slate-800">{renderFilters()}</div>}

      {/* Content */}
      <div className="min-h-[300px]">
        {isLoading && renderLoadingState()}
        {!isLoading && filteredRefunds.length === 0 && renderEmptyState()}
        {!isLoading && filteredRefunds.length > 0 && (
          <div>{filteredRefunds.map(renderRefundRow)}</div>
        )}
      </div>

      {/* Pagination */}
      {!isLoading && filteredRefunds.length > 0 && renderPagination()}
    </div>
  );
};

export default RefundList;
