/**
 * InvoiceDetail Component
 * Modal displaying full invoice details with line items
 */

import React, { useState, useEffect } from 'react';
import {
  X,
  Download,
  Mail,
  Printer,
  Copy,
  Check,
  FileText,
  Calendar,
  CreditCard,
  Building,
  AlertCircle,
  CheckCircle,
  Clock,
  Loader2,
} from 'lucide-react';
import { getInvoiceById, downloadInvoice } from '../../services/payment.service';
import type { Invoice, InvoiceLineItem } from '../../types/payment.types';

// Extended Invoice type for component display (includes additional fields)
type InvoiceStatus = 'draft' | 'open' | 'paid' | 'void' | 'uncollectible' | 'pending' | 'failed' | 'refunded';

interface InvoiceData extends Omit<Invoice, 'status' | 'lineItems' | 'description'> {
  status: InvoiceStatus;
  description: string;
  taxRate?: number;
  discount?: number;
  lineItems: InvoiceLineItem[];
  billingDetails?: {
    name: string;
    email: string;
    company?: string;
    address?: {
      line1: string;
      line2?: string;
      city: string;
      state: string;
      postalCode: string;
      country: string;
    };
  };
  paymentMethod?: {
    type: string;
    last4?: string;
    brand?: string;
  };
}

interface InvoiceDetailProps {
  invoiceId: string;
  onClose: () => void;
  onDownload?: (invoiceId: string) => void;
}

const InvoiceDetail: React.FC<InvoiceDetailProps> = ({
  invoiceId,
  onClose,
  onDownload,
}) => {
  const [invoice, setInvoice] = useState<InvoiceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    const fetchInvoice = async () => {
      setLoading(true);
      setError(null);

      try {
        const data = await getInvoiceById(invoiceId);
        // Map Invoice from service to InvoiceData (add required fields)
        const invoiceData: InvoiceData = {
          ...data,
          description: data.description ?? `Invoice ${data.number}`,
          lineItems: data.lineItems ?? [],
        };
        setInvoice(invoiceData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load invoice');
      } finally {
        setLoading(false);
      }
    };

    fetchInvoice();
  }, [invoiceId]);

  const handleDownload = async () => {
    setDownloading(true);
    try {
      if (onDownload) {
        onDownload(invoiceId);
      } else {
        await downloadInvoice(invoiceId);
      }
    } catch (err) {
      console.error('Download failed:', err);
    } finally {
      setDownloading(false);
    }
  };

  const handleCopyLink = async () => {
    const invoiceUrl = `${window.location.origin}/invoices/${invoiceId}`;
    await navigator.clipboard.writeText(invoiceUrl);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

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

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const formatAmount = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency.toUpperCase(),
    }).format(amount);
  };

  const getStatusBadge = (status: InvoiceData['status']) => {
    const styles: Record<InvoiceStatus, { bg: string; text: string; icon: typeof CheckCircle }> = {
      paid: { bg: 'bg-green-500/20', text: 'text-green-400', icon: CheckCircle },
      pending: { bg: 'bg-yellow-500/20', text: 'text-yellow-400', icon: Clock },
      failed: { bg: 'bg-red-500/20', text: 'text-red-400', icon: AlertCircle },
      refunded: { bg: 'bg-blue-500/20', text: 'text-blue-400', icon: CheckCircle },
      void: { bg: 'bg-gray-500/20', text: 'text-gray-400', icon: AlertCircle },
      draft: { bg: 'bg-gray-500/20', text: 'text-gray-400', icon: Clock },
      open: { bg: 'bg-blue-500/20', text: 'text-blue-400', icon: Clock },
      uncollectible: { bg: 'bg-red-500/20', text: 'text-red-400', icon: AlertCircle },
    };

    const style = styles[status];
    const Icon = style.icon;

    return (
      <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium ${style.bg} ${style.text}`}>
        <Icon className="w-4 h-4" />
        <span className="capitalize">{status}</span>
      </span>
    );
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
      <div className="w-full max-w-2xl max-h-[90vh] overflow-hidden bg-gray-800 rounded-xl shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-600/20 rounded-lg">
              <FileText className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-white">Invoice Details</h2>
              {invoice && (
                <p className="text-sm text-gray-400">{invoice.number}</p>
              )}
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="overflow-y-auto max-h-[calc(90vh-140px)] p-4">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 text-blue-400 animate-spin" />
            </div>
          ) : error ? (
            <div className="text-center py-12">
              <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
              <p className="text-gray-400">{error}</p>
            </div>
          ) : invoice ? (
            <div className="space-y-6">
              {/* Status & Dates */}
              <div className="flex flex-wrap items-center justify-between gap-4 pb-4 border-b border-gray-700">
                {getStatusBadge(invoice.status)}
                <div className="flex items-center gap-4 text-sm text-gray-400">
                  <div className="flex items-center gap-1.5">
                    <Calendar className="w-4 h-4" />
                    <span>Issued: {formatDate(invoice.createdAt)}</span>
                  </div>
                  {invoice.paidAt && (
                    <div className="flex items-center gap-1.5">
                      <CheckCircle className="w-4 h-4 text-green-400" />
                      <span>Paid: {formatDate(invoice.paidAt)}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Billing Details */}
              {invoice.billingDetails && (
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-4 bg-gray-900/50 rounded-lg">
                    <div className="flex items-center gap-2 mb-3">
                      <Building className="w-4 h-4 text-gray-500" />
                      <span className="text-sm font-medium text-gray-400">Bill To</span>
                    </div>
                    <p className="text-white font-medium">{invoice.billingDetails.name}</p>
                    {invoice.billingDetails.company && (
                      <p className="text-gray-400 text-sm">{invoice.billingDetails.company}</p>
                    )}
                    <p className="text-gray-400 text-sm">{invoice.billingDetails.email}</p>
                    {invoice.billingDetails.address && (
                      <p className="text-gray-500 text-sm mt-2">
                        {invoice.billingDetails.address.line1}
                        {invoice.billingDetails.address.line2 && <>, {invoice.billingDetails.address.line2}</>}
                        <br />
                        {invoice.billingDetails.address.city}, {invoice.billingDetails.address.state} {invoice.billingDetails.address.postalCode}
                      </p>
                    )}
                  </div>

                  {invoice.paymentMethod && (
                    <div className="p-4 bg-gray-900/50 rounded-lg">
                      <div className="flex items-center gap-2 mb-3">
                        <CreditCard className="w-4 h-4 text-gray-500" />
                        <span className="text-sm font-medium text-gray-400">Payment Method</span>
                      </div>
                      <p className="text-white">
                        {invoice.paymentMethod.brand} •••• {invoice.paymentMethod.last4}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Line Items */}
              <div>
                <h3 className="text-sm font-medium text-gray-400 mb-3">Items</h3>
                <div className="bg-gray-900/50 rounded-lg overflow-hidden">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-gray-700">
                        <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Description</th>
                        <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Qty</th>
                        <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Unit Price</th>
                        <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Amount</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-700/50">
                      {invoice.lineItems.map((item) => (
                        <tr key={item.id}>
                          <td className="py-3 px-4 text-white">{item.description}</td>
                          <td className="py-3 px-4 text-center text-gray-400">{item.quantity}</td>
                          <td className="py-3 px-4 text-right text-gray-400 font-mono">
                            {formatAmount(item.unitPrice, invoice.currency)}
                          </td>
                          <td className="py-3 px-4 text-right text-white font-mono">
                            {formatAmount(item.amount, invoice.currency)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Totals */}
              <div className="flex justify-end">
                <div className="w-64 space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Subtotal</span>
                    <span className="text-white font-mono">{formatAmount(invoice.subtotal, invoice.currency)}</span>
                  </div>
                  {invoice.discount && invoice.discount > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">Discount</span>
                      <span className="text-green-400 font-mono">-{formatAmount(invoice.discount, invoice.currency)}</span>
                    </div>
                  )}
                  {invoice.tax > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-400">
                        Tax {invoice.taxRate && `(${invoice.taxRate}%)`}
                      </span>
                      <span className="text-white font-mono">{formatAmount(invoice.tax, invoice.currency)}</span>
                    </div>
                  )}
                  <div className="flex justify-between pt-2 border-t border-gray-700">
                    <span className="text-white font-medium">Total</span>
                    <span className="text-white font-bold font-mono text-lg">
                      {formatAmount(invoice.amount, invoice.currency)}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          ) : null}
        </div>

        {/* Footer Actions */}
        {invoice && (
          <div className="flex items-center justify-between p-4 border-t border-gray-700 bg-gray-800/50">
            <div className="flex items-center gap-2">
              <button
                onClick={handleCopyLink}
                className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              >
                {copied ? (
                  <>
                    <Check className="w-4 h-4 text-green-400" />
                    Copied
                  </>
                ) : (
                  <>
                    <Copy className="w-4 h-4" />
                    Copy Link
                  </>
                )}
              </button>
              <button
                onClick={handlePrint}
                className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              >
                <Printer className="w-4 h-4" />
                Print
              </button>
            </div>
            <button
              onClick={handleDownload}
              disabled={downloading}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
            >
              {downloading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Downloading...
                </>
              ) : (
                <>
                  <Download className="w-4 h-4" />
                  Download PDF
                </>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default InvoiceDetail;
