/**
 * Return Detail Page
 * View return details
 */

'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { returnsAPI } from '@/lib/api/returns';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Modal,
  Input,
  Select,
} from '@/components/ui';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, CheckCircle, DollarSign } from 'lucide-react';
import toast from 'react-hot-toast';
import Link from 'next/link';

export default function ReturnDetailPage() {
  const router = useRouter();
  const params = useParams();
  const returnId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showRefundModal, setShowRefundModal] = useState(false);
  const [refundMethod, setRefundMethod] = useState('CREDIT_NOTE');
  const [refundAmount, setRefundAmount] = useState('');
  const [replacementProductId, setReplacementProductId] = useState('');
  const [refundReference, setRefundReference] = useState('');

  // Fetch return details
  const { data: returnRecord, isLoading, error, refetch } = useQuery({
    queryKey: ['return', returnId],
    queryFn: async () => {
      if (isNaN(returnId)) {
        throw new Error('Invalid Return ID');
      }
      const response = await returnsAPI.getById(returnId);
      return response?.data || response;
    },
    enabled: !isNaN(returnId),
  });

  // Complete return mutation
  const completeReturnMutation = useMutation({
    mutationFn: async (refundData) => {
      return await returnsAPI.complete(returnId, refundData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['return', returnId]);
      queryClient.invalidateQueries(['returns']);
      queryClient.invalidateQueries(['credit-notes']);
      toast.success('Return completed successfully!');
      setShowRefundModal(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || error.message || 'Failed to complete return.');
    },
  });

  const handleCompleteReturn = () => {
    setRefundAmount(returnRecord?.total_amount?.toString() || '');
    setShowRefundModal(true);
  };

  const handleProcessRefund = async () => {
    // Ensure refund_method is set (default to CREDIT_NOTE)
    const finalRefundMethod = refundMethod || 'CREDIT_NOTE';
    
    const refundData = {
      refund_method: finalRefundMethod,
      refund_amount: refundAmount ? parseFloat(refundAmount) : returnRecord.total_amount,
      ...(replacementProductId && { replacement_product_id: parseInt(replacementProductId) }),
      ...(refundReference && { refund_reference: refundReference }),
    };

    await completeReturnMutation.mutateAsync(refundData);
  };

  if (isLoading) {
    return <LoadingPage message="Loading return details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!returnRecord) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Return not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const getStatusVariant = (status) => {
    switch (status) {
      case 'COMPLETED':
        return 'success';
      case 'DRAFT':
        return 'warning';
      default:
        return 'default';
    }
  };

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Returns
        </Button>
        {returnRecord.status === 'DRAFT' && (
          <Button variant="primary" onClick={handleCompleteReturn} disabled={completeReturnMutation.isLoading}>
            <DollarSign className="w-4 h-4 mr-2" />
            {completeReturnMutation.isLoading ? 'Processing...' : 'Process Refund'}
          </Button>
        )}
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <span>Return #{returnRecord.id}</span>
            </div>
            <Badge variant={getStatusVariant(returnRecord.status)}>{returnRecord.status}</Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Original Sale:</span>{' '}
                <Link href={`/sales/${returnRecord.sale_id}`} className="text-blue-600 hover:underline">
                  Sale #{returnRecord.sale_id}
                </Link>
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Date:</span> {formatDateTime(returnRecord.created_at)}
              </p>
              {returnRecord.reason && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Reason:</span> {returnRecord.reason}
                </p>
              )}
            </div>
            <div>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Subtotal:</span> {formatCurrency(returnRecord.subtotal)}
              </p>
              <p className="text-lg font-bold text-gray-800">
                <span className="font-medium">Total:</span> {formatCurrency(returnRecord.total_amount)}
              </p>
              {returnRecord.status === 'COMPLETED' && returnRecord.refund_method && (
                <div className="mt-3 pt-3 border-t space-y-2">
                  <p className="text-sm text-gray-600">
                    <span className="font-medium">Refund Method:</span>{' '}
                    <Badge variant={returnRecord.refund_method === 'CREDIT_NOTE' ? 'warning' : 'success'}>
                      {returnRecord.refund_method}
                    </Badge>
                  </p>
                  {returnRecord.refund_amount && (
                    <p className="text-sm text-gray-600">
                      <span className="font-medium">Refund Amount:</span>{' '}
                      {formatCurrency(returnRecord.refund_amount)}
                    </p>
                  )}
                  {returnRecord.refunded_at && (
                    <p className="text-sm text-gray-600">
                      <span className="font-medium">Refunded:</span>{' '}
                      {formatDateTime(returnRecord.refunded_at)}
                    </p>
                  )}
                  {returnRecord.refund_reference && (
                    <p className="text-sm text-gray-600">
                      <span className="font-medium">Reference:</span>{' '}
                      <span className="font-mono">{returnRecord.refund_reference}</span>
                    </p>
                  )}
                  {returnRecord.replacementProduct && (
                    <p className="text-sm text-gray-600">
                      <span className="font-medium">Replacement:</span>{' '}
                      {returnRecord.replacementProduct.name}
                    </p>
                  )}
                </div>
              )}
              {returnRecord.creditNotes && returnRecord.creditNotes.length > 0 && (
                <div className="mt-3 pt-3 border-t">
                  <p className="text-sm text-gray-600 mb-1">
                    <span className="font-medium">Credit Note:</span>{' '}
                    <span className="font-mono">
                      {returnRecord.creditNotes[0].kra_receipt_no || returnRecord.creditNotes[0].receipt_number || `CN-${returnRecord.creditNotes[0].id}`}
                    </span>
                  </p>
                </div>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-2">Return Info</h3>
              {returnRecord.sale?.invoice_no && (
                <p className="text-gray-600 mb-1">
                  <span className="font-medium">Invoice:</span>{' '}
                  <span className="font-mono">{returnRecord.sale.invoice_no}</span>
                </p>
              )}
              {returnRecord.returned_at && (
                <p className="text-gray-600 mb-1">
                  <span className="font-medium">Returned:</span>{' '}
                  {formatDateTime(returnRecord.returned_at)}
                </p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {returnRecord.items && returnRecord.items.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Return Items</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Product</TableHead>
                  <TableHead align="right">Quantity</TableHead>
                  <TableHead align="right">Unit Price</TableHead>
                  <TableHead align="right">Total</TableHead>
                  <TableHead>Reason</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {returnRecord.items.map((item) => (
                  <TableRow key={item.id}>
                      <TableCell>
                        <div>
                          <div className="font-medium">
                            {item.sale_item?.product?.name || 'Unknown Product'}
                          </div>
                          {item.sale_item?.product?.sku && (
                            <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                              SKU: {item.sale_item.product.sku}
                            </div>
                          )}
                        </div>
                      </TableCell>
                    <TableCell align="right">{item.quantity}</TableCell>
                    <TableCell align="right">{formatCurrency(item.unit_price)}</TableCell>
                    <TableCell align="right">{formatCurrency(item.subtotal)}</TableCell>
                    <TableCell>{item.reason || 'N/A'}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Refund Processing Modal */}
      <Modal
        isOpen={showRefundModal}
        onClose={() => setShowRefundModal(false)}
        title="Process Refund"
        size="md"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Refund Method <span className="text-red-500">*</span>
            </label>
            <Select
              value={refundMethod || 'CREDIT_NOTE'}
              onChange={(e) => setRefundMethod(e.target.value)}
              options={[
                { value: 'CREDIT_NOTE', label: 'Credit Note' },
                { value: 'CASH', label: 'Cash' },
                { value: 'CARD', label: 'Card' },
                { value: 'MPESA', label: 'M-Pesa' },
                { value: 'REPLACEMENT', label: 'Replacement Product' },
              ]}
              placeholder="Select refund method"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Refund Amount
            </label>
            <Input
              type="number"
              step="0.01"
              min="0"
              value={refundAmount}
              onChange={(e) => setRefundAmount(e.target.value)}
              placeholder={`Default: ${formatCurrency(returnRecord?.total_amount || 0)}`}
            />
            <p className="mt-1 text-xs text-gray-500">
              Leave empty to use total amount: {formatCurrency(returnRecord?.total_amount || 0)}
            </p>
          </div>

          {refundMethod === 'REPLACEMENT' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Replacement Product ID (Optional)
              </label>
              <Input
                type="number"
                value={replacementProductId}
                onChange={(e) => setReplacementProductId(e.target.value)}
                placeholder="Enter product ID"
              />
            </div>
          )}

          {(refundMethod === 'CARD' || refundMethod === 'MPESA') && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Transaction Reference
              </label>
              <Input
                type="text"
                value={refundReference}
                onChange={(e) => setRefundReference(e.target.value)}
                placeholder="Enter transaction ID/reference"
              />
            </div>
          )}

          <div className="flex gap-3 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => setShowRefundModal(false)}
              className="flex-1"
              disabled={completeReturnMutation.isLoading}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              onClick={handleProcessRefund}
              className="flex-1"
              disabled={completeReturnMutation.isLoading}
              loading={completeReturnMutation.isLoading}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              Process Refund
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

