/**
 * InvoicePreview Component
 * Pre-checkout invoice preview with itemized breakdown
 * Epic: OQI-005 Pagos y Stripe
 */

import React, { useMemo } from 'react';
import {
  FileText,
  Calendar,
  CreditCard,
  Tag,
  Percent,
  DollarSign,
  CheckCircle,
  AlertCircle,
  Info,
  ChevronRight,
  X,
  Loader2,
} from 'lucide-react';

// Types
export interface InvoiceLineItem {
  id: string;
  description: string;
  quantity: number;
  unitPrice: number;
  amount: number;
  type: 'subscription' | 'addon' | 'usage' | 'proration' | 'credit';
}

export interface InvoiceDiscount {
  id: string;
  code: string;
  type: 'percentage' | 'fixed';
  value: number;
  amount: number;
  expiresAt?: Date;
}

export interface InvoiceTax {
  id: string;
  name: string;
  rate: number;
  amount: number;
  jurisdiction?: string;
}

export interface InvoicePreviewData {
  id?: string;
  planName: string;
  planId: string;
  billingCycle: 'monthly' | 'yearly';
  lineItems: InvoiceLineItem[];
  discounts: InvoiceDiscount[];
  taxes: InvoiceTax[];
  subtotal: number;
  totalDiscount: number;
  totalTax: number;
  total: number;
  currency: string;
  effectiveDate: Date;
  nextBillingDate: Date;
  paymentMethodLast4?: string;
  paymentMethodBrand?: string;
}

export interface InvoicePreviewProps {
  invoice: InvoicePreviewData;
  onConfirm?: () => void;
  onCancel?: () => void;
  onEditPayment?: () => void;
  onEditBilling?: () => void;
  onRemoveCoupon?: (discountId: string) => void;
  isProcessing?: boolean;
  showActions?: boolean;
  compact?: boolean;
}

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

// Date formatter
const formatDate = (date: Date) => {
  return new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  }).format(date);
};

// Line item type badge
const LineItemTypeBadge: React.FC<{ type: InvoiceLineItem['type'] }> = ({ type }) => {
  const styles = {
    subscription: 'bg-blue-900/50 text-blue-400',
    addon: 'bg-purple-900/50 text-purple-400',
    usage: 'bg-amber-900/50 text-amber-400',
    proration: 'bg-emerald-900/50 text-emerald-400',
    credit: 'bg-emerald-900/50 text-emerald-400',
  };

  return (
    <span className={`px-2 py-0.5 rounded text-xs font-medium ${styles[type]}`}>
      {type.charAt(0).toUpperCase() + type.slice(1)}
    </span>
  );
};

const InvoicePreview: React.FC<InvoicePreviewProps> = ({
  invoice,
  onConfirm,
  onCancel,
  onEditPayment,
  onEditBilling,
  onRemoveCoupon,
  isProcessing = false,
  showActions = true,
  compact = false,
}) => {
  // Calculate savings for yearly billing
  const yearlySavings = useMemo(() => {
    if (invoice.billingCycle === 'yearly') {
      // Assume 20% savings on yearly plans
      const monthlyEquivalent = invoice.subtotal / 12;
      const monthlyCost = monthlyEquivalent * 1.25; // What it would cost monthly
      return (monthlyCost * 12) - invoice.subtotal;
    }
    return 0;
  }, [invoice.billingCycle, invoice.subtotal]);

  // Render line items section
  const renderLineItems = () => (
    <div className="space-y-3">
      <h4 className="text-slate-400 text-sm font-medium flex items-center gap-2">
        <FileText className="w-4 h-4" />
        Items
      </h4>
      <div className="space-y-2">
        {invoice.lineItems.map((item) => (
          <div
            key={item.id}
            className="flex items-center justify-between py-2 border-b border-slate-800 last:border-0"
          >
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span className="text-white">{item.description}</span>
                {!compact && <LineItemTypeBadge type={item.type} />}
              </div>
              {item.quantity > 1 && (
                <span className="text-slate-500 text-sm">
                  {item.quantity} x {formatCurrency(item.unitPrice, invoice.currency)}
                </span>
              )}
            </div>
            <span className={`font-medium ${item.amount < 0 ? 'text-emerald-400' : 'text-white'}`}>
              {item.amount < 0 ? '-' : ''}{formatCurrency(Math.abs(item.amount), invoice.currency)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );

  // Render discounts section
  const renderDiscounts = () => {
    if (invoice.discounts.length === 0) return null;

    return (
      <div className="space-y-3">
        <h4 className="text-slate-400 text-sm font-medium flex items-center gap-2">
          <Tag className="w-4 h-4" />
          Discounts
        </h4>
        <div className="space-y-2">
          {invoice.discounts.map((discount) => (
            <div
              key={discount.id}
              className="flex items-center justify-between py-2 bg-emerald-900/20 rounded-lg px-3 border border-emerald-800/50"
            >
              <div className="flex items-center gap-2">
                <Percent className="w-4 h-4 text-emerald-400" />
                <div>
                  <span className="text-emerald-400 font-medium">{discount.code}</span>
                  <span className="text-slate-400 text-sm ml-2">
                    ({discount.type === 'percentage' ? `${discount.value}% off` : formatCurrency(discount.value, invoice.currency)})
                  </span>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-emerald-400 font-medium">
                  -{formatCurrency(discount.amount, invoice.currency)}
                </span>
                {onRemoveCoupon && (
                  <button
                    onClick={() => onRemoveCoupon(discount.id)}
                    className="text-slate-500 hover:text-red-400 transition-colors"
                    title="Remove coupon"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // Render taxes section
  const renderTaxes = () => {
    if (invoice.taxes.length === 0) return null;

    return (
      <div className="space-y-2">
        {invoice.taxes.map((tax) => (
          <div key={tax.id} className="flex items-center justify-between text-sm">
            <span className="text-slate-400">
              {tax.name} ({tax.rate}%)
              {tax.jurisdiction && <span className="text-slate-500"> - {tax.jurisdiction}</span>}
            </span>
            <span className="text-slate-300">{formatCurrency(tax.amount, invoice.currency)}</span>
          </div>
        ))}
      </div>
    );
  };

  // Render summary section
  const renderSummary = () => (
    <div className="space-y-3 pt-4 border-t border-slate-700">
      {/* Subtotal */}
      <div className="flex justify-between">
        <span className="text-slate-400">Subtotal</span>
        <span className="text-white">{formatCurrency(invoice.subtotal, invoice.currency)}</span>
      </div>

      {/* Discounts */}
      {invoice.totalDiscount > 0 && (
        <div className="flex justify-between">
          <span className="text-slate-400">Discounts</span>
          <span className="text-emerald-400">-{formatCurrency(invoice.totalDiscount, invoice.currency)}</span>
        </div>
      )}

      {/* Taxes */}
      {renderTaxes()}

      {/* Yearly Savings */}
      {yearlySavings > 0 && (
        <div className="flex justify-between py-2 bg-blue-900/20 rounded-lg px-3 border border-blue-800/50">
          <span className="text-blue-400 flex items-center gap-2">
            <CheckCircle className="w-4 h-4" />
            Yearly savings
          </span>
          <span className="text-blue-400 font-medium">
            {formatCurrency(yearlySavings, invoice.currency)}/year
          </span>
        </div>
      )}

      {/* Total */}
      <div className="flex justify-between pt-3 border-t border-slate-700">
        <span className="text-white font-semibold text-lg">Total due today</span>
        <span className="text-white font-bold text-xl">
          {formatCurrency(invoice.total, invoice.currency)}
        </span>
      </div>
    </div>
  );

  // Render billing details
  const renderBillingDetails = () => (
    <div className="grid grid-cols-2 gap-4 pt-4 border-t border-slate-700">
      {/* Billing Cycle */}
      <div>
        <span className="text-slate-500 text-xs block mb-1">Billing Cycle</span>
        <span className="text-white capitalize">{invoice.billingCycle}</span>
      </div>

      {/* Effective Date */}
      <div>
        <span className="text-slate-500 text-xs block mb-1">Effective Date</span>
        <span className="text-white">{formatDate(invoice.effectiveDate)}</span>
      </div>

      {/* Next Billing Date */}
      <div>
        <span className="text-slate-500 text-xs block mb-1">Next Billing Date</span>
        <span className="text-white">{formatDate(invoice.nextBillingDate)}</span>
      </div>

      {/* Payment Method */}
      {invoice.paymentMethodLast4 && (
        <div>
          <span className="text-slate-500 text-xs block mb-1">Payment Method</span>
          <div className="flex items-center gap-2">
            <CreditCard className="w-4 h-4 text-slate-400" />
            <span className="text-white">
              {invoice.paymentMethodBrand || 'Card'} ****{invoice.paymentMethodLast4}
            </span>
            {onEditPayment && (
              <button
                onClick={onEditPayment}
                className="text-blue-400 text-sm hover:text-blue-300"
              >
                Change
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );

  // Compact view
  if (compact) {
    return (
      <div className="bg-slate-900 rounded-lg border border-slate-800 p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-blue-400" />
            <span className="text-white font-medium">{invoice.planName}</span>
          </div>
          <span className="text-white font-bold">
            {formatCurrency(invoice.total, invoice.currency)}
          </span>
        </div>

        {invoice.totalDiscount > 0 && (
          <div className="text-emerald-400 text-sm mb-2">
            Includes {formatCurrency(invoice.totalDiscount, invoice.currency)} discount
          </div>
        )}

        <div className="text-slate-400 text-sm flex items-center gap-1">
          <Calendar className="w-4 h-4" />
          Next billing: {formatDate(invoice.nextBillingDate)}
        </div>
      </div>
    );
  }

  // Full view
  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">
            <div className="w-10 h-10 rounded-lg bg-blue-600/20 flex items-center justify-center">
              <FileText className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <h2 className="text-white font-semibold">Invoice Preview</h2>
              <p className="text-slate-400 text-sm">{invoice.planName} - {invoice.billingCycle} plan</p>
            </div>
          </div>
          {invoice.id && (
            <span className="text-slate-500 text-sm font-mono">#{invoice.id}</span>
          )}
        </div>
      </div>

      {/* Content */}
      <div className="p-6 space-y-6">
        {/* Line Items */}
        {renderLineItems()}

        {/* Discounts */}
        {renderDiscounts()}

        {/* Summary */}
        {renderSummary()}

        {/* Billing Details */}
        {!compact && renderBillingDetails()}

        {/* Info Notice */}
        <div className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-lg">
          <Info className="w-5 h-5 text-slate-400 flex-shrink-0 mt-0.5" />
          <div className="text-slate-400 text-sm">
            <p>
              By confirming, you authorize us to charge your payment method for{' '}
              <span className="text-white font-medium">
                {formatCurrency(invoice.total, invoice.currency)}
              </span>{' '}
              today and automatically on each billing date until you cancel.
            </p>
            <p className="mt-2">
              You can cancel anytime from your billing settings. Refunds are available
              within 14 days of purchase.
            </p>
          </div>
        </div>
      </div>

      {/* Actions */}
      {showActions && (
        <div className="p-6 border-t border-slate-800 flex justify-between">
          <button
            onClick={onCancel}
            disabled={isProcessing}
            className="px-4 py-2 text-slate-300 hover:text-white transition-colors disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            disabled={isProcessing}
            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"
          >
            {isProcessing ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Processing...
              </>
            ) : (
              <>
                <DollarSign className="w-4 h-4" />
                Confirm Payment
                <ChevronRight className="w-4 h-4" />
              </>
            )}
          </button>
        </div>
      )}
    </div>
  );
};

export default InvoicePreview;
