/**
 * Sale Detail Page
 * View sale details with items and payment info
 */

'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { salesAPI } from '@/lib/api/sales';
import { Button, Card, CardHeader, CardTitle, CardContent, Badge, LoadingSpinner } from '@/components/ui';
import { SALE_STATUSES } from '@/lib/utils/constants';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, Receipt, Printer, CreditCard } from 'lucide-react';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui';
import PaymentModal from '@/components/features/pos/PaymentModal';
import toast from 'react-hot-toast';

export default function SaleDetailPage() {
  const router = useRouter();
  const params = useParams();
  const queryClient = useQueryClient();
  const saleId = parseInt(params.id);
  const [showPaymentModal, setShowPaymentModal] = useState(false);

  // Fetch sale details
  const { data, isLoading, error } = useQuery({
    queryKey: ['sale', saleId],
    queryFn: async () => {
      const response = await salesAPI.getById(saleId);
      // API returns { success: true, data: { sale } }
      // axios interceptor returns response.data, so response is { success: true, data: { sale } }
      return response?.data?.sale || null;
    },
  });

  const sale = data;

  // Handle payment completion
  const handlePaymentComplete = () => {
    // Invalidate sale query to refresh data
    queryClient.invalidateQueries(['sale', saleId]);
    queryClient.invalidateQueries(['sales']); // Also refresh sales list
    setShowPaymentModal(false);
    toast.success('Payment completed successfully! Sale updated to PAID.');
  };

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  if (error || !sale) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">
                {error?.response?.data?.message || 'Sale not found'}
              </p>
              <Button onClick={() => router.push('/sales')} variant="outline">
                Back to Sales
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const getStatusBadge = (status) => {
    const variants = {
      PAID: 'success',
      DRAFT: 'warning',
      CANCELLED: 'danger',
    };
    return <Badge variant={variants[status] || 'default'}>{status}</Badge>;
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => router.push('/sales')}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
              Sale {sale.invoice_no || `#${sale.id}`}
            </h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {formatDateTime(sale.created_at)}
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          {getStatusBadge(sale.status)}
          {sale.status === 'DRAFT' && (
            <Button
              variant="primary"
              className="flex items-center gap-2"
              onClick={() => setShowPaymentModal(true)}
            >
              <CreditCard className="w-4 h-4" />
              Complete Payment
            </Button>
          )}
          <Button
            variant="outline"
            className="flex items-center gap-2"
          >
            <Printer className="w-4 h-4" />
            Print Receipt
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Sale Items */}
          {sale.items && sale.items.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Sale Items</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Product</TableHead>
                      <TableHead>Variant</TableHead>
                      <TableHead align="right">Quantity</TableHead>
                      <TableHead align="right">Unit Price</TableHead>
                      <TableHead align="right">Discount</TableHead>
                      <TableHead align="right">Total</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sale.items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>
                          <div>
                            <div className="font-medium">
                              {item.product?.name || item.variant?.product?.name || 'Unknown Product'}
                            </div>
                            {item.variant && item.variant.attributes && (
                              <div className="text-xs text-gray-500 mt-1">
                                {Object.entries(item.variant.attributes)
                                  .map(([key, value]) => `${key}: ${value}`)
                                  .join(', ')}
                              </div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {item.variant ? (
                            <Badge variant="info">Variant</Badge>
                          ) : (
                            <span className="text-gray-400">Standard</span>
                          )}
                        </TableCell>
                        <TableCell align="right">
                          <span className="font-medium">{item.quantity}</span>
                        </TableCell>
                        <TableCell align="right">
                          {formatCurrency(item.unit_price)}
                        </TableCell>
                        <TableCell align="right">
                          {item.discount_amount ? formatCurrency(item.discount_amount) : '-'}
                        </TableCell>
                        <TableCell align="right">
                          <span className="font-medium">{formatCurrency(item.total)}</span>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          {/* Payment Information */}
          {sale.payments && sale.payments.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Payment Information</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Method</TableHead>
                      <TableHead>Reference</TableHead>
                      <TableHead>Date</TableHead>
                      <TableHead align="right">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sale.payments.map((payment) => (
                      <TableRow key={payment.id}>
                        <TableCell>
                          <Badge variant="info">{payment.payment_method}</Badge>
                        </TableCell>
                        <TableCell>
                          <span className="font-mono text-sm">
                            {payment.reference_number || 'N/A'}
                          </span>
                        </TableCell>
                        <TableCell>
                          {formatDateTime(payment.created_at)}
                        </TableCell>
                        <TableCell align="right">
                          <span className="font-medium">{formatCurrency(payment.amount)}</span>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Sale Summary */}
          <Card>
            <CardHeader>
              <CardTitle>Sale Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex justify-between">
                <span className="text-gray-600">Subtotal</span>
                <span className="font-medium">{formatCurrency(sale.subtotal)}</span>
              </div>
              {sale.discount_amount > 0 && (
                <div className="flex justify-between text-red-600">
                  <span>Discount</span>
                  <span>-{formatCurrency(sale.discount_amount)}</span>
                </div>
              )}
              {sale.vat > 0 && (
                <div className="flex justify-between">
                  <span className="text-gray-600">VAT</span>
                  <span>{formatCurrency(sale.vat)}</span>
                </div>
              )}
              <div className="border-t pt-4 flex justify-between text-lg font-bold">
                <span>Total</span>
                <span>{formatCurrency(sale.total)}</span>
              </div>
            </CardContent>
          </Card>

          {/* Customer Information */}
          {sale.customer && (
            <Card>
              <CardHeader>
                <CardTitle>Customer</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                <div>
                  <p className="text-sm text-gray-500">Name</p>
                  <p className="font-medium">{sale.customer.name}</p>
                </div>
                {sale.customer.email && (
                  <div>
                    <p className="text-sm text-gray-500">Email</p>
                    <p>{sale.customer.email}</p>
                  </div>
                )}
                {sale.customer.phone && (
                  <div>
                    <p className="text-sm text-gray-500">Phone</p>
                    <p>{sale.customer.phone}</p>
                  </div>
                )}
                {sale.customer.kra_pin && (
                  <div>
                    <p className="text-sm text-gray-500">KRA PIN</p>
                    <p className="font-mono text-sm">{sale.customer.kra_pin}</p>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Sale Information */}
          <Card>
            <CardHeader>
              <CardTitle>Sale Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div>
                <p className="text-sm text-gray-500">Sale Type</p>
                <Badge variant="info">{sale.sale_type}</Badge>
              </div>
              {sale.user && (
                <div>
                  <p className="text-sm text-gray-500">Cashier</p>
                  <p className="font-medium">{sale.user.full_name || sale.user.username}</p>
                </div>
              )}
              <div>
                <p className="text-sm text-gray-500">Created</p>
                <p className="text-sm">{formatDateTime(sale.created_at)}</p>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Payment Modal */}
      {showPaymentModal && sale && (
        <PaymentModal
          isOpen={showPaymentModal}
          onClose={() => setShowPaymentModal(false)}
          total={sale.total}
          saleId={sale.id}
          onPaymentComplete={handlePaymentComplete}
          onManualMPesaConfirm={(paymentId) => {
            // Handle manual M-Pesa confirmation if needed
            toast('M-Pesa payment confirmation required');
          }}
        />
      )}
    </div>
  );
}

