/**
 * RefundsPage
 * Standalone page for viewing and managing refund requests
 * Route: /billing/refunds
 * Epic: OQI-005 Pagos y Stripe
 */

import React, { useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import {
  RotateCcw,
  ArrowLeft,
  RefreshCw,
  Loader2,
  AlertCircle,
  Filter,
  X,
  Clock,
  CheckCircle,
  XCircle,
} from 'lucide-react';
import {
  useRefunds,
  useCancelRefund,
  useRefundEligibility,
  useRequestRefund,
} from '../../../hooks/usePayments';
import { usePaymentStore } from '../../../stores/paymentStore';
import RefundList from '../../../components/payments/RefundList';
import RefundRequestModal from '../../../components/payments/RefundRequestModal';
import type { RefundStatus, RefundReason } from '../../../types/payment.types';
import type { Refund } from '../../../components/payments/RefundList';

const ITEMS_PER_PAGE = 10;

const STATUS_OPTIONS: { value: RefundStatus | 'all'; label: string }[] = [
  { value: 'all', label: 'All Statuses' },
  { value: 'pending', label: 'Pending' },
  { value: 'processing', label: 'Processing' },
  { value: 'completed', label: 'Completed' },
  { value: 'failed', label: 'Failed' },
  { value: 'canceled', label: 'Canceled' },
];

export default function RefundsPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<RefundStatus | 'all'>('all');
  const [showFilters, setShowFilters] = useState(false);
  const [showRefundModal, setShowRefundModal] = useState(false);

  const { currentSubscription } = usePaymentStore();

  const offset = (currentPage - 1) * ITEMS_PER_PAGE;
  const { data, isLoading, error, refetch } = useRefunds({
    limit: ITEMS_PER_PAGE,
    offset,
    status: statusFilter !== 'all' ? statusFilter : undefined,
  });

  const { data: eligibility } = useRefundEligibility(currentSubscription?.id);
  const cancelRefund = useCancelRefund();
  const requestRefund = useRequestRefund();

  const handlePageChange = useCallback((page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  const handleCancelRefund = useCallback(async (refundId: string) => {
    if (!confirm('Are you sure you want to cancel this refund request?')) return;
    try {
      await cancelRefund.mutateAsync(refundId);
    } catch (err) {
      console.error('Failed to cancel refund:', err);
    }
  }, [cancelRefund]);

  const handleRetryRefund = useCallback((refundId: string) => {
    // For now, just show a message - in production this would re-process
    alert(`Retry refund ${refundId} - This would re-process the refund request`);
  }, []);

  const handleViewInvoice = useCallback((invoiceId: string) => {
    window.location.href = `/billing/invoices?invoiceId=${invoiceId}`;
  }, []);

  const handleRequestRefund = useCallback(async (data: {
    subscriptionId: string;
    amount: number;
    reason: RefundReason;
    reasonDetails?: string;
    refundMethod: 'original' | 'wallet';
  }) => {
    await requestRefund.mutateAsync({
      subscriptionId: data.subscriptionId,
      amount: data.amount,
      reason: data.reason,
      reasonDetails: data.reasonDetails,
      refundMethod: data.refundMethod,
    });
  }, [requestRefund]);

  const clearFilters = useCallback(() => {
    setStatusFilter('all');
    setCurrentPage(1);
  }, []);

  const hasActiveFilters = statusFilter !== 'all';

  // Calculate stats from current page data
  const stats = {
    total: data?.total ?? 0,
    pending: data?.refunds.filter((r) => r.status === 'pending').length ?? 0,
    completed: data?.refunds.filter((r) => r.status === 'completed').length ?? 0,
    totalAmount: data?.refunds.reduce((sum, r) => sum + r.amount, 0) ?? 0,
  };

  // Map refunds to component format (already strings, just need to ensure correct shape)
  const mappedRefunds: Refund[] = (data?.refunds ?? []).map((r) => ({
    id: r.id,
    subscriptionId: r.subscriptionId,
    subscriptionName: r.subscriptionName,
    invoiceId: r.invoiceId,
    amount: r.amount,
    currency: r.currency,
    reason: r.reason,
    reasonDetails: r.reasonDetails,
    status: r.status,
    refundMethod: r.refundMethod,
    requestedAt: r.requestedAt,
    processedAt: r.processedAt,
    failureReason: r.failureReason,
    transactionId: r.transactionId,
  }));

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/billing"
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white flex items-center gap-3">
              <div className="p-2 bg-blue-600/20 rounded-lg">
                <RotateCcw className="w-6 h-6 text-blue-400" />
              </div>
              Refunds
            </h1>
            <p className="text-gray-400 mt-1">
              View and manage your refund requests
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {eligibility?.eligible && currentSubscription && (
            <button
              onClick={() => setShowRefundModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
            >
              <RotateCcw className="w-4 h-4" />
              Request Refund
            </button>
          )}
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              showFilters || hasActiveFilters
                ? 'bg-blue-600/20 text-blue-400 border border-blue-600/50'
                : 'bg-gray-800 text-gray-400 hover:text-white border border-gray-700'
            }`}
          >
            <Filter className="w-4 h-4" />
            Filters
            {hasActiveFilters && (
              <span className="w-2 h-2 bg-blue-400 rounded-full" />
            )}
          </button>
          <button
            onClick={() => refetch()}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-400 hover:text-white rounded-lg transition-colors border border-gray-700 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-white font-medium">Filter Refunds</h3>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="flex items-center gap-1.5 text-sm text-gray-400 hover:text-white transition-colors"
              >
                <X className="w-4 h-4" />
                Clear filters
              </button>
            )}
          </div>
          <div className="flex flex-wrap gap-2">
            {STATUS_OPTIONS.map((option) => (
              <button
                key={option.value}
                onClick={() => {
                  setStatusFilter(option.value as RefundStatus | 'all');
                  setCurrentPage(1);
                }}
                className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                  statusFilter === option.value
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-800 text-gray-400 hover:text-white border border-gray-700'
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Summary Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
          <div className="flex items-center gap-2 text-gray-400 text-sm mb-1">
            <RotateCcw className="w-4 h-4" />
            Total Requests
          </div>
          <p className="text-2xl font-bold text-white">{stats.total}</p>
        </div>
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
          <div className="flex items-center gap-2 text-amber-400 text-sm mb-1">
            <Clock className="w-4 h-4" />
            Pending
          </div>
          <p className="text-2xl font-bold text-amber-400">{stats.pending}</p>
        </div>
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
          <div className="flex items-center gap-2 text-green-400 text-sm mb-1">
            <CheckCircle className="w-4 h-4" />
            Completed
          </div>
          <p className="text-2xl font-bold text-green-400">{stats.completed}</p>
        </div>
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
          <p className="text-gray-400 text-sm">Total Refunded</p>
          <p className="text-2xl font-bold text-white mt-1">
            ${stats.totalAmount.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </p>
        </div>
      </div>

      {/* Eligibility Notice */}
      {currentSubscription && eligibility && (
        <div className={`p-4 rounded-xl border ${
          eligibility.eligible
            ? 'bg-blue-900/20 border-blue-800/50'
            : 'bg-gray-800/50 border-gray-700'
        }`}>
          <div className="flex items-start gap-3">
            {eligibility.eligible ? (
              <CheckCircle className="w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5" />
            ) : (
              <XCircle className="w-5 h-5 text-gray-500 flex-shrink-0 mt-0.5" />
            )}
            <div>
              <p className={eligibility.eligible ? 'text-blue-400 font-medium' : 'text-gray-400'}>
                {eligibility.eligible
                  ? `You are eligible for a refund of up to $${eligibility.refundableAmount.toFixed(2)}`
                  : 'You are not currently eligible for a refund'}
              </p>
              {eligibility.eligible && (
                <p className="text-gray-500 text-sm mt-1">
                  {eligibility.daysRemaining} days remaining in the {eligibility.maxRefundDays}-day refund window
                </p>
              )}
              {!eligibility.eligible && eligibility.reason && (
                <p className="text-gray-500 text-sm mt-1">{eligibility.reason}</p>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Refund List */}
      {error ? (
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-12 text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
          <p className="text-gray-400 mb-4">
            {error instanceof Error ? error.message : 'Failed to load refunds'}
          </p>
          <button
            onClick={() => refetch()}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm"
          >
            Retry
          </button>
        </div>
      ) : (
        <RefundList
          refunds={mappedRefunds}
          totalCount={data?.total ?? 0}
          currentPage={currentPage}
          pageSize={ITEMS_PER_PAGE}
          onPageChange={handlePageChange}
          onViewInvoice={handleViewInvoice}
          onRetryRefund={handleRetryRefund}
          onCancelRefund={handleCancelRefund}
          isLoading={isLoading}
          showFilters={false}
        />
      )}

      {/* Refund Request Modal */}
      {showRefundModal && currentSubscription && eligibility && (
        <RefundRequestModal
          isOpen={showRefundModal}
          onClose={() => setShowRefundModal(false)}
          subscriptionId={currentSubscription.id}
          subscriptionName={currentSubscription.plan?.name ?? currentSubscription.planName}
          eligibility={eligibility}
          onSubmit={handleRequestRefund}
          onSuccess={() => {
            setShowRefundModal(false);
            refetch();
          }}
        />
      )}

      {/* Loading indicator for mutations */}
      {(cancelRefund.isPending || requestRefund.isPending) && (
        <div className="fixed bottom-4 right-4 flex items-center gap-2 px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg shadow-xl">
          <Loader2 className="w-4 h-4 text-blue-400 animate-spin" />
          <span className="text-white text-sm">
            {cancelRefund.isPending ? 'Canceling refund...' : 'Processing refund request...'}
          </span>
        </div>
      )}
    </div>
  );
}
