/**
 * RefundRequestModal Component
 * Modal for requesting refunds on subscriptions/purchases
 * Epic: OQI-005 Pagos y Stripe
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  RotateCcw,
  AlertCircle,
  CheckCircle,
  X,
  Clock,
  DollarSign,
  Info,
  Loader2,
  Calendar,
  CreditCard,
  MessageSquare,
} from 'lucide-react';

// Types
export interface RefundEligibility {
  eligible: boolean;
  refundableAmount: number;
  originalAmount: number;
  daysRemaining: number;
  maxRefundDays: number;
  partialRefundAllowed: boolean;
  reason?: string;
}

export interface RefundRequestData {
  subscriptionId: string;
  amount: number;
  reason: RefundReason;
  reasonDetails?: string;
  refundMethod: 'original' | 'wallet';
}

export type RefundReason =
  | 'changed_mind'
  | 'not_needed'
  | 'duplicate_charge'
  | 'service_issue'
  | 'billing_error'
  | 'other';

export interface RefundRequestModalProps {
  isOpen: boolean;
  onClose: () => void;
  subscriptionId: string;
  subscriptionName: string;
  eligibility: RefundEligibility;
  onSubmit?: (data: RefundRequestData) => Promise<void>;
  onSuccess?: (refundId: string) => void;
}

const REFUND_REASONS: { value: RefundReason; label: string; requiresDetails: boolean }[] = [
  { value: 'changed_mind', label: 'Changed my mind', requiresDetails: false },
  { value: 'not_needed', label: "Don't need the service anymore", requiresDetails: false },
  { value: 'duplicate_charge', label: 'Duplicate or incorrect charge', requiresDetails: true },
  { value: 'service_issue', label: 'Service not working as expected', requiresDetails: true },
  { value: 'billing_error', label: 'Billing or pricing error', requiresDetails: true },
  { value: 'other', label: 'Other reason', requiresDetails: true },
];

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

const RefundRequestModal: React.FC<RefundRequestModalProps> = ({
  isOpen,
  onClose,
  subscriptionId,
  subscriptionName,
  eligibility,
  onSubmit,
  onSuccess,
}) => {
  const [step, setStep] = useState<'form' | 'confirm' | 'success'>('form');
  const [selectedReason, setSelectedReason] = useState<RefundReason | ''>('');
  const [reasonDetails, setReasonDetails] = useState('');
  const [refundAmount, setRefundAmount] = useState<number>(eligibility.refundableAmount);
  const [refundMethod, setRefundMethod] = useState<'original' | 'wallet'>('original');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [refundId, setRefundId] = useState<string | null>(null);

  // Check if details are required
  const requiresDetails = useMemo(() => {
    const reason = REFUND_REASONS.find((r) => r.value === selectedReason);
    return reason?.requiresDetails || false;
  }, [selectedReason]);

  // Form validation
  const isFormValid = useMemo(() => {
    if (!selectedReason) return false;
    if (requiresDetails && reasonDetails.trim().length < 10) return false;
    if (refundAmount <= 0 || refundAmount > eligibility.refundableAmount) return false;
    return true;
  }, [selectedReason, requiresDetails, reasonDetails, refundAmount, eligibility.refundableAmount]);

  // Handle amount change
  const handleAmountChange = useCallback((value: string) => {
    const amount = parseFloat(value) || 0;
    setRefundAmount(Math.min(amount, eligibility.refundableAmount));
  }, [eligibility.refundableAmount]);

  // Handle submit
  const handleSubmit = useCallback(async () => {
    if (!isFormValid || !onSubmit) return;

    setIsSubmitting(true);
    setError(null);

    try {
      await onSubmit({
        subscriptionId,
        amount: refundAmount,
        reason: selectedReason as RefundReason,
        reasonDetails: requiresDetails ? reasonDetails : undefined,
        refundMethod,
      });

      // Generate mock refund ID for success state
      const mockRefundId = `ref_${Date.now().toString(36)}`;
      setRefundId(mockRefundId);
      setStep('success');
      onSuccess?.(mockRefundId);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to process refund request');
    } finally {
      setIsSubmitting(false);
    }
  }, [isFormValid, onSubmit, subscriptionId, refundAmount, selectedReason, requiresDetails, reasonDetails, refundMethod, onSuccess]);

  // Reset state on close
  const handleClose = useCallback(() => {
    setStep('form');
    setSelectedReason('');
    setReasonDetails('');
    setRefundAmount(eligibility.refundableAmount);
    setRefundMethod('original');
    setError(null);
    setRefundId(null);
    onClose();
  }, [onClose, eligibility.refundableAmount]);

  // Render not eligible state
  const renderNotEligible = () => (
    <div className="p-6 text-center">
      <div className="w-16 h-16 rounded-full bg-red-900/20 flex items-center justify-center mx-auto mb-4">
        <AlertCircle className="w-8 h-8 text-red-400" />
      </div>
      <h3 className="text-white text-xl font-semibold mb-2">Refund Not Available</h3>
      <p className="text-slate-400 mb-4">
        {eligibility.reason || 'This subscription is not eligible for a refund.'}
      </p>
      {eligibility.daysRemaining < 0 && (
        <p className="text-slate-500 text-sm">
          The {eligibility.maxRefundDays}-day refund window has expired.
        </p>
      )}
      <button
        onClick={handleClose}
        className="mt-6 px-6 py-2 bg-slate-800 text-white rounded-lg hover:bg-slate-700 transition-colors"
      >
        Close
      </button>
    </div>
  );

  // Render form step
  const renderFormStep = () => (
    <div className="space-y-6">
      {/* Eligibility Info */}
      <div className="bg-blue-900/20 border border-blue-800/50 rounded-lg p-4">
        <div className="flex items-center gap-3">
          <Clock className="w-5 h-5 text-blue-400" />
          <div>
            <p className="text-blue-400 font-medium">Refund Window</p>
            <p className="text-slate-400 text-sm">
              {eligibility.daysRemaining} days remaining of {eligibility.maxRefundDays}-day policy
            </p>
          </div>
        </div>
      </div>

      {/* Refund Amount */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">
          Refund Amount
        </label>
        {eligibility.partialRefundAllowed ? (
          <div className="relative">
            <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
            <input
              type="number"
              value={refundAmount}
              onChange={(e) => handleAmountChange(e.target.value)}
              max={eligibility.refundableAmount}
              min={0}
              step="0.01"
              className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-10 pr-4 py-3 text-white focus:border-blue-500 focus:outline-none"
            />
          </div>
        ) : (
          <div className="bg-slate-800 border border-slate-700 rounded-lg px-4 py-3">
            <span className="text-white text-lg font-semibold">
              {formatCurrency(eligibility.refundableAmount)}
            </span>
            <span className="text-slate-500 text-sm ml-2">(Full refund)</span>
          </div>
        )}
        <p className="text-slate-500 text-xs mt-1">
          Maximum refundable: {formatCurrency(eligibility.refundableAmount)} of{' '}
          {formatCurrency(eligibility.originalAmount)} original charge
        </p>
      </div>

      {/* Refund Reason */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">
          Reason for Refund
        </label>
        <div className="space-y-2">
          {REFUND_REASONS.map((reason) => (
            <label
              key={reason.value}
              className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
                selectedReason === reason.value
                  ? 'border-blue-500 bg-blue-900/20'
                  : 'border-slate-700 bg-slate-800/50 hover:border-slate-600'
              }`}
            >
              <input
                type="radio"
                name="refundReason"
                value={reason.value}
                checked={selectedReason === reason.value}
                onChange={(e) => setSelectedReason(e.target.value as RefundReason)}
                className="sr-only"
              />
              <div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${
                selectedReason === reason.value
                  ? 'border-blue-500 bg-blue-500'
                  : 'border-slate-600'
              }`}>
                {selectedReason === reason.value && (
                  <div className="w-2 h-2 rounded-full bg-white" />
                )}
              </div>
              <span className="text-white">{reason.label}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Details (if required) */}
      {requiresDetails && (
        <div>
          <label className="block text-slate-300 text-sm font-medium mb-2">
            Please provide details
            <span className="text-red-400 ml-1">*</span>
          </label>
          <textarea
            value={reasonDetails}
            onChange={(e) => setReasonDetails(e.target.value)}
            placeholder="Please describe your issue..."
            rows={3}
            minLength={10}
            className="w-full bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-white resize-none focus:border-blue-500 focus:outline-none"
          />
          <p className="text-slate-500 text-xs mt-1">
            Minimum 10 characters ({reasonDetails.length}/10)
          </p>
        </div>
      )}

      {/* Refund Method */}
      <div>
        <label className="block text-slate-300 text-sm font-medium mb-2">
          Refund To
        </label>
        <div className="grid grid-cols-2 gap-3">
          <button
            onClick={() => setRefundMethod('original')}
            className={`p-4 rounded-lg border text-left transition-colors ${
              refundMethod === 'original'
                ? 'border-blue-500 bg-blue-900/20'
                : 'border-slate-700 bg-slate-800/50 hover:border-slate-600'
            }`}
          >
            <CreditCard className="w-5 h-5 text-slate-400 mb-2" />
            <p className="text-white font-medium">Original Payment</p>
            <p className="text-slate-400 text-xs">3-5 business days</p>
          </button>
          <button
            onClick={() => setRefundMethod('wallet')}
            className={`p-4 rounded-lg border text-left transition-colors ${
              refundMethod === 'wallet'
                ? 'border-blue-500 bg-blue-900/20'
                : 'border-slate-700 bg-slate-800/50 hover:border-slate-600'
            }`}
          >
            <DollarSign className="w-5 h-5 text-slate-400 mb-2" />
            <p className="text-white font-medium">Wallet Balance</p>
            <p className="text-slate-400 text-xs">Instant credit</p>
          </button>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="flex items-center gap-2 p-3 bg-red-900/20 border border-red-800/50 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-400" />
          <span className="text-red-400 text-sm">{error}</span>
        </div>
      )}
    </div>
  );

  // Render confirm step
  const renderConfirmStep = () => {
    const selectedReasonLabel = REFUND_REASONS.find((r) => r.value === selectedReason)?.label;

    return (
      <div className="space-y-6">
        <div className="text-center">
          <div className="w-16 h-16 rounded-full bg-amber-900/20 flex items-center justify-center mx-auto mb-4">
            <RotateCcw className="w-8 h-8 text-amber-400" />
          </div>
          <h3 className="text-white text-xl font-semibold">Confirm Refund Request</h3>
          <p className="text-slate-400 mt-1">Please review the details below</p>
        </div>

        <div className="bg-slate-800/50 rounded-lg p-4 space-y-3">
          <div className="flex justify-between">
            <span className="text-slate-400">Subscription</span>
            <span className="text-white">{subscriptionName}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-400">Refund Amount</span>
            <span className="text-white font-semibold">{formatCurrency(refundAmount)}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-400">Reason</span>
            <span className="text-white">{selectedReasonLabel}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-400">Refund To</span>
            <span className="text-white capitalize">{refundMethod === 'original' ? 'Original payment' : 'Wallet'}</span>
          </div>
          {reasonDetails && (
            <div className="pt-3 border-t border-slate-700">
              <span className="text-slate-400 text-sm block mb-1">Additional Details</span>
              <p className="text-slate-300 text-sm">{reasonDetails}</p>
            </div>
          )}
        </div>

        <div className="flex items-start gap-3 p-4 bg-amber-900/20 rounded-lg border border-amber-800/50">
          <Info className="w-5 h-5 text-amber-400 flex-shrink-0 mt-0.5" />
          <p className="text-slate-300 text-sm">
            This action cannot be undone. Your subscription will be canceled immediately
            upon refund approval.
          </p>
        </div>
      </div>
    );
  };

  // Render success step
  const renderSuccessStep = () => (
    <div className="p-6 text-center">
      <div className="w-16 h-16 rounded-full bg-emerald-900/20 flex items-center justify-center mx-auto mb-4">
        <CheckCircle className="w-8 h-8 text-emerald-400" />
      </div>
      <h3 className="text-white text-xl font-semibold mb-2">Refund Requested</h3>
      <p className="text-slate-400 mb-4">
        Your refund request has been submitted successfully.
      </p>
      <div className="bg-slate-800/50 rounded-lg p-4 mb-6">
        <p className="text-slate-500 text-sm">Reference Number</p>
        <p className="text-white font-mono">{refundId}</p>
      </div>
      <div className="space-y-2 text-left bg-slate-800/50 rounded-lg p-4 mb-6">
        <p className="text-white font-medium">What happens next?</p>
        <ul className="text-slate-400 text-sm space-y-1">
          <li>1. Our team will review your request within 24 hours</li>
          <li>2. You'll receive an email confirmation once approved</li>
          <li>3. {refundMethod === 'original'
            ? 'Funds will be returned to your original payment method in 3-5 business days'
            : 'Funds will be credited to your wallet instantly'}</li>
        </ul>
      </div>
      <button
        onClick={handleClose}
        className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 transition-colors"
      >
        Done
      </button>
    </div>
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={step === 'success' ? handleClose : undefined}
      />

      {/* Modal */}
      <div className="relative w-full max-w-lg bg-slate-900 rounded-xl border border-slate-800 shadow-2xl mx-4 max-h-[90vh] overflow-hidden">
        {/* Header */}
        {step !== 'success' && (
          <div className="flex items-center justify-between p-6 border-b border-slate-800">
            <div className="flex items-center gap-3">
              <RotateCcw className="w-6 h-6 text-blue-400" />
              <h2 className="text-white text-lg font-semibold">Request Refund</h2>
            </div>
            <button
              onClick={handleClose}
              className="text-slate-400 hover:text-white transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        )}

        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[60vh]">
          {!eligibility.eligible && renderNotEligible()}
          {eligibility.eligible && step === 'form' && renderFormStep()}
          {eligibility.eligible && step === 'confirm' && renderConfirmStep()}
          {step === 'success' && renderSuccessStep()}
        </div>

        {/* Footer */}
        {eligibility.eligible && step !== 'success' && (
          <div className="flex justify-between gap-4 p-6 border-t border-slate-800">
            <button
              onClick={step === 'form' ? handleClose : () => setStep('form')}
              disabled={isSubmitting}
              className="px-4 py-2 text-slate-300 hover:text-white transition-colors disabled:opacity-50"
            >
              {step === 'form' ? 'Cancel' : 'Back'}
            </button>
            <button
              onClick={step === 'form' ? () => setStep('confirm') : handleSubmit}
              disabled={!isFormValid || isSubmitting}
              className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Processing...
                </>
              ) : step === 'form' ? (
                'Continue'
              ) : (
                'Submit Request'
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default RefundRequestModal;
