/**
 * Sales List Page
 * Display and manage sales
 */

'use client';

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

export default function SalesPage() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [statusFilter, setStatusFilter] = useState('');
  const [saleTypeFilter, setSaleTypeFilter] = useState('');
  const [selectedSale, setSelectedSale] = useState(null);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [paymentSale, setPaymentSale] = useState(null);

  // Fetch sales
  const { data, isLoading, error } = useQuery({
    queryKey: ['sales', page, limit, statusFilter, saleTypeFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(statusFilter && { status: statusFilter }),
        ...(saleTypeFilter && { sale_type: saleTypeFilter }),
      };
      const response = await salesAPI.list(params);
      return response.data || response;
    },
  });

  // Cancel sale mutation
  const cancelSaleMutation = useMutation({
    mutationFn: async (saleId) => {
      return await salesAPI.cancel(saleId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['sales']);
      toast.success('Sale cancelled successfully');
      setShowCancelModal(false);
      setSelectedSale(null);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Failed to cancel sale');
    },
  });

  const sales = data?.sales || [];
  const pagination = data?.pagination || {};

  const handleCancel = (sale) => {
    setSelectedSale(sale);
    setShowCancelModal(true);
  };

  const confirmCancel = () => {
    if (selectedSale) {
      cancelSaleMutation.mutate(selectedSale.id);
    }
  };

  const handleCompletePayment = (sale) => {
    setPaymentSale(sale);
    setShowPaymentModal(true);
  };

  const handlePaymentComplete = () => {
    queryClient.invalidateQueries(['sales']);
    setShowPaymentModal(false);
    setPaymentSale(null);
    toast.success('Payment completed successfully! Sale updated to PAID.');
  };

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

  return (
    <div className="p-6 space-y-6 bg-gray-50 dark:bg-gray-950">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Sales</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            View and manage sales transactions
          </p>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Status
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Statuses</option>
                <option value="PAID">Paid</option>
                <option value="DRAFT">Draft</option>
                <option value="CANCELLED">Cancelled</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Sale Type
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={saleTypeFilter}
                onChange={(e) => {
                  setSaleTypeFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Types</option>
                <option value="POS">POS</option>
                <option value="INVOICE">Invoice</option>
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Sales Table */}
      <Card>
        <CardHeader>
          <CardTitle>Sales List</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center py-12">
              <LoadingSpinner size="lg" />
            </div>
          ) : error ? (
            <div className="text-center py-12 text-red-600 dark:text-red-400">
              Error loading sales. Please try again.
            </div>
          ) : sales.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Receipt className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No sales found</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Invoice #</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Customer</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Total</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sales.map((sale) => (
                    <TableRow key={sale.id}>
                      <TableCell>
                        <span className="font-mono font-medium">{sale.invoice_no || `#${sale.id}`}</span>
                      </TableCell>
                      <TableCell>
                        {formatDateTime(sale.created_at)}
                      </TableCell>
                      <TableCell>
                        {sale.customer ? (
                          <div>
                            <div className="font-medium">{sale.customer.name}</div>
                            {sale.customer.email && (
                              <div className="text-xs text-gray-500">{sale.customer.email}</div>
                            )}
                          </div>
                        ) : (
                          <span className="text-gray-400">Walk-in</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant="info">{sale.sale_type}</Badge>
                      </TableCell>
                      <TableCell>
                        {getStatusBadge(sale.status)}
                      </TableCell>
                      <TableCell align="right">
                        <span className="font-medium">{formatCurrency(sale.total)}</span>
                      </TableCell>
                      <TableCell align="right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/sales/${sale.id}`)}
                            title="View details"
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          {sale.status === 'DRAFT' && (
                            <>
                              <Button
                                variant="primary"
                                size="sm"
                                onClick={() => handleCompletePayment(sale)}
                                title="Complete payment"
                              >
                                <CreditCard className="w-4 h-4" />
                              </Button>
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleCancel(sale)}
                                title="Cancel sale"
                              >
                                <X className="w-4 h-4" />
                              </Button>
                            </>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {/* Pagination */}
              {pagination.totalPages > 1 && (
                <div className="mt-4 flex items-center justify-between">
                  <div className="text-sm text-gray-700 dark:text-gray-300">
                    Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} sales
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.max(1, p - 1))}
                      disabled={page === 1}
                    >
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.min(pagination.totalPages, p + 1))}
                      disabled={page === pagination.totalPages}
                    >
                      Next
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* Cancel Sale Modal */}
      <Modal
        isOpen={showCancelModal}
        onClose={() => {
          setShowCancelModal(false);
          setSelectedSale(null);
        }}
        title="Cancel Sale"
      >
        {selectedSale && (
          <div className="space-y-4">
            <p className="text-gray-600">
              Are you sure you want to cancel sale <strong>{selectedSale.invoice_no || `#${selectedSale.id}`}</strong>?
            </p>
            <p className="text-sm text-gray-500">
              This action cannot be undone. Reserved inventory will be released.
            </p>
            <div className="flex justify-end gap-3 mt-6">
              <Button
                variant="outline"
                onClick={() => {
                  setShowCancelModal(false);
                  setSelectedSale(null);
                }}
                disabled={cancelSaleMutation.isPending}
              >
                Cancel
              </Button>
              <Button
                variant="danger"
                onClick={confirmCancel}
                loading={cancelSaleMutation.isPending}
              >
                Confirm Cancel
              </Button>
            </div>
          </div>
        )}
      </Modal>

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

