/**
 * New Return Page
 * Create a new return from a sale by searching invoice number
 */

'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, useFieldArray } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { returnsAPI } from '@/lib/api/returns';
import { salesAPI } from '@/lib/api/sales';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Input,
  LoadingSpinner,
} from '@/components/ui';
import { ArrowLeft, Search, QrCode, CheckCircle2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';

const returnItemSchema = z.object({
  sale_item_id: z.number().int().positive(),
  inventory_item_id: z.number().int().positive().nullable().optional(),
  quantity: z.number().positive(),
  reason: z.string().max(255).optional(),
});

const returnSchema = z.object({
  sale_id: z.number().int().positive('Please select a sale'),
  reason: z.string().max(1000).optional(),
  items: z.array(returnItemSchema).min(1, 'At least one return item is required'),
});

export default function NewReturnPage() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [invoiceSearch, setInvoiceSearch] = useState('');
  const [selectedSaleId, setSelectedSaleId] = useState(null);
  const [selectedItemIds, setSelectedItemIds] = useState(new Set());

  // Search sale by invoice number
  const { data: searchData, isLoading: isSearching, refetch: searchSale } = useQuery({
    queryKey: ['sales', 'search', invoiceSearch],
    queryFn: async () => {
      if (!invoiceSearch.trim()) return null;
      const response = await salesAPI.list({ 
        invoice_no: invoiceSearch.trim(),
        status: 'PAID',
        limit: 5 // Get up to 5 matches
      });
      const sales = response?.data?.sales || response?.sales || [];
      // Try exact match first, then first result
      const exactMatch = sales.find(s => 
        s.invoice_no?.toUpperCase() === invoiceSearch.trim().toUpperCase()
      );
      return exactMatch || (sales.length > 0 ? sales[0] : null);
    },
    enabled: false, // Don't auto-search, wait for button click or Enter
  });

  // Fetch selected sale details
  const { data: saleData, isLoading: isLoadingSale } = useQuery({
    queryKey: ['sale', selectedSaleId],
    queryFn: async () => {
      if (!selectedSaleId) return null;
      const response = await salesAPI.getById(selectedSaleId);
      return response?.data?.sale || response?.sale || null;
    },
    enabled: !!selectedSaleId,
  });

  const foundSale = searchData;
  const sale = saleData || foundSale;

  const {
    register,
    handleSubmit,
    control,
    watch,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(returnSchema),
    defaultValues: {
      sale_id: null,
      reason: '',
      items: [],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items',
  });

  // Watch form values
  const saleId = watch('sale_id');
  const items = watch('items');

  // Handle invoice search
  const handleSearch = async () => {
    if (!invoiceSearch.trim()) {
      toast.error('Please enter an invoice number');
      return;
    }
    
    try {
      const result = await searchSale();
      const foundSale = result?.data;
      
      if (foundSale) {
        setSelectedSaleId(foundSale.id);
        setValue('sale_id', foundSale.id);
        setSelectedItemIds(new Set()); // Reset selected items
        setValue('items', []); // Clear items
        toast.success('Sale found! Select items to return.');
      } else {
        toast.error('Sale not found. Please check the invoice number.');
      }
    } catch (error) {
      console.error('Search error:', error);
      toast.error('Error searching for sale. Please try again.');
    }
  };

  // Handle Enter key in invoice search
  const handleInvoiceSearchKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSearch();
    }
  };

  // Toggle item selection
  const toggleItemSelection = (saleItemId, maxQuantity) => {
    const newSelected = new Set(selectedItemIds);
    if (newSelected.has(saleItemId)) {
      newSelected.delete(saleItemId);
      // Remove from form items
      const itemIndex = fields.findIndex(f => f.sale_item_id === saleItemId);
      if (itemIndex !== -1) {
        remove(itemIndex);
      }
    } else {
      newSelected.add(saleItemId);
      // Add to form items with quantity 0
      const saleItem = sale?.items?.find(si => si.id === saleItemId);
      if (saleItem) {
        append({
          sale_item_id: saleItem.id,
          inventory_item_id: saleItem.inventory_item_id || null,
          quantity: 0,
          reason: '',
        });
      }
    }
    setSelectedItemIds(newSelected);
  };

  // Populate items when sale is loaded
  useEffect(() => {
    if (sale && sale.items && sale.items.length > 0) {
      // Clear existing items when sale changes
      if (sale.id !== selectedSaleId) {
        setSelectedItemIds(new Set());
        setValue('items', []);
      }
    }
  }, [sale, selectedSaleId, setValue]);

  // Create return mutation
  const createReturnMutation = useMutation({
    mutationFn: async (data) => {
      return await returnsAPI.create(data);
    },
    onSuccess: (response) => {
      const returnId = response?.data?.id || response?.id;
      queryClient.invalidateQueries(['returns']);
      toast.success('Return created successfully!');
      router.push(`/returns/${returnId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create return';
      toast.error(message);
    },
  });

  const onSubmit = (data) => {
    // Filter out items with quantity 0
    const validItems = data.items
      .filter(item => item.quantity > 0)
      .map(item => {
        // Remove inventory_item_id if it's null/undefined (for quantity-based items)
        const cleanedItem = {
          sale_item_id: item.sale_item_id,
          quantity: item.quantity,
          ...(item.reason && { reason: item.reason }),
          // Only include inventory_item_id if it's a valid number (UID-tracked items)
          ...(item.inventory_item_id && item.inventory_item_id > 0 && { 
            inventory_item_id: item.inventory_item_id 
          }),
        };
        return cleanedItem;
      });
    
    if (validItems.length === 0) {
      toast.error('Please specify quantities for at least one item to return');
      return;
    }

    createReturnMutation.mutate({
      sale_id: data.sale_id,
      reason: data.reason || null,
      items: validItems,
    });
  };

  // Calculate totals
  const calculateItemTotal = (item) => {
    if (!sale?.items) return 0;
    const saleItem = sale.items.find(si => si.id === item.sale_item_id);
    if (!saleItem) return 0;
    return parseFloat(saleItem.unit_price || 0) * parseFloat(item.quantity || 0);
  };

  const totalAmount = items.reduce((sum, item) => sum + calculateItemTotal(item), 0);

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          onClick={() => router.back()}
          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">Create Return</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Search invoice number and select items to return
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Form */}
          <div className="lg:col-span-2 space-y-6">
            {/* Invoice Search */}
            <Card>
              <CardHeader>
                <CardTitle>Search Sale by Invoice Number</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Invoice Number / QR Code <span className="text-red-500">*</span>
                  </label>
                  <div className="flex gap-2">
                    <div className="flex-1 relative">
                      <Input
                        type="text"
                        placeholder="Enter invoice number or scan QR code (e.g., INV-20260119-00006)"
                        value={invoiceSearch}
                        onChange={(e) => setInvoiceSearch(e.target.value)}
                        onKeyPress={handleInvoiceSearchKeyPress}
                        leftIcon={<QrCode className="w-4 h-4" />}
                        disabled={isSearching}
                        className="w-full"
                      />
                    </div>
                    <Button
                      type="button"
                      onClick={handleSearch}
                      disabled={!invoiceSearch.trim() || isSearching}
                      loading={isSearching}
                      variant="primary"
                      className="flex items-center gap-2"
                    >
                      <Search className="w-4 h-4" />
                      Search
                    </Button>
                  </div>
                  <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                    Enter the invoice number from the receipt or scan the QR code
                  </p>
                </div>

                {/* Sale Found Display */}
                {sale && (
                  <div className="mt-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                    <div className="flex items-center gap-2 mb-3">
                      <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
                      <h3 className="font-semibold text-green-900 dark:text-green-100">Sale Found</h3>
                    </div>
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      <div>
                        <span className="text-gray-600 dark:text-gray-400">Invoice:</span>{' '}
                        <span className="font-mono font-medium">{sale.invoice_no || `#${sale.id}`}</span>
                      </div>
                      <div>
                        <span className="text-gray-600 dark:text-gray-400">Sale ID:</span>{' '}
                        <span className="font-medium">#{sale.id}</span>
                      </div>
                      <div>
                        <span className="text-gray-600 dark:text-gray-400">Total:</span>{' '}
                        <span className="font-medium">{formatCurrency(sale.total || 0)}</span>
                      </div>
                      <div>
                        <span className="text-gray-600 dark:text-gray-400">Date:</span>{' '}
                        <span className="font-medium">{formatDateTime(sale.created_at)}</span>
                      </div>
                    </div>
                    {sale.items && (
                      <div className="mt-2">
                        <span className="text-gray-600 dark:text-gray-400">Items:</span>{' '}
                        <span className="font-medium">{sale.items.length}</span>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Return Items Selection */}
            {sale && sale.items && sale.items.length > 0 && (
              <Card>
                <CardHeader>
                  <CardTitle>Select Items to Return</CardTitle>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                    Click on items to select them for return, then specify quantities and reasons
                  </p>
                </CardHeader>
                <CardContent className="space-y-4">
                  {isLoadingSale ? (
                    <div className="flex justify-center py-8">
                      <LoadingSpinner />
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {sale.items.map((saleItem) => {
                        const product = saleItem.product;
                        const maxQuantity = saleItem.quantity || 0;
                        const isSelected = selectedItemIds.has(saleItem.id);
                        const itemField = fields.find(f => f.sale_item_id === saleItem.id);
                        const itemIndex = fields.findIndex(f => f.sale_item_id === saleItem.id);

                        return (
                          <div
                            key={saleItem.id}
                            className={`p-4 border-2 rounded-lg transition-all ${
                              isSelected
                                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                                : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 cursor-pointer'
                            }`}
                            onClick={() => toggleItemSelection(saleItem.id, maxQuantity)}
                          >
                            {/* Item Header - Clickable */}
                            <div className="flex items-start justify-between mb-3">
                              <div className="flex items-start gap-3 flex-1">
                                <div
                                  className={`mt-1 w-5 h-5 rounded border-2 flex items-center justify-center flex-shrink-0 ${
                                    isSelected
                                      ? 'border-blue-600 bg-blue-600'
                                      : 'border-gray-300 dark:border-gray-600'
                                  }`}
                                >
                                  {isSelected && (
                                    <CheckCircle2 className="w-4 h-4 text-white" />
                                  )}
                                </div>
                                <div className="flex-1">
                                  <h4 className="font-medium text-gray-900 dark:text-white">
                                    {product?.name || 'Unknown Product'}
                                  </h4>
                                  {product?.sku && (
                                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                                      SKU: {product.sku}
                                    </p>
                                  )}
                                  <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                                    Original: {maxQuantity} × {formatCurrency(saleItem.unit_price || 0)} = {formatCurrency((saleItem.unit_price || 0) * maxQuantity)}
                                  </p>
                                </div>
                              </div>
                            </div>

                            {/* Return Details - Only show when selected */}
                            {isSelected && itemField && (
                              <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 space-y-4">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                  <div>
                                    <Input
                                      label={`Quantity to Return (Max: ${maxQuantity})`}
                                      type="number"
                                      step="1"
                                      min="1"
                                      max={maxQuantity}
                                      {...register(`items.${itemIndex}.quantity`, { valueAsNumber: true })}
                                      error={errors.items?.[itemIndex]?.quantity?.message}
                                      onClick={(e) => e.stopPropagation()}
                                    />
                                  </div>
                                  <div>
                                    <Input
                                      label="Reason (Optional)"
                                      type="text"
                                      placeholder="Reason for return"
                                      {...register(`items.${itemIndex}.reason`)}
                                      error={errors.items?.[itemIndex]?.reason?.message}
                                      onClick={(e) => e.stopPropagation()}
                                    />
                                  </div>
                                </div>

                                {/* Hidden fields */}
                                <input
                                  type="hidden"
                                  {...register(`items.${itemIndex}.sale_item_id`, { valueAsNumber: true })}
                                  value={saleItem.id}
                                />
                                {saleItem.inventory_item_id && (
                                  <input
                                    type="hidden"
                                    {...register(`items.${itemIndex}.inventory_item_id`, { valueAsNumber: true })}
                                    value={saleItem.inventory_item_id}
                                  />
                                )}

                                {errors.items?.[itemIndex] && (
                                  <p className="text-sm text-red-600" onClick={(e) => e.stopPropagation()}>
                                    {errors.items[itemIndex]?.message}
                                  </p>
                                )}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  )}

                  {errors.items && (
                    <p className="text-sm text-red-600">{errors.items.message}</p>
                  )}

                  {selectedItemIds.size === 0 && (
                    <p className="text-center py-8 text-gray-500 dark:text-gray-400">
                      Select items above to include in the return
                    </p>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Return Reason */}
            {sale && (
              <Card>
                <CardHeader>
                  <CardTitle>Return Reason</CardTitle>
                </CardHeader>
                <CardContent>
                  <Input
                    label="General Reason (Optional)"
                    type="text"
                    placeholder="Overall reason for this return"
                    {...register('reason')}
                    error={errors.reason?.message}
                  />
                </CardContent>
              </Card>
            )}
          </div>

          {/* Summary Sidebar */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Return Summary</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {sale ? (
                  <>
                    <div className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600 dark:text-gray-400">Selected Items:</span>
                        <span className="font-medium">{selectedItemIds.size}</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600 dark:text-gray-400">Items with Quantity:</span>
                        <span className="font-medium">{items.filter(i => i.quantity > 0).length}</span>
                      </div>
                      <div className="pt-2 border-t">
                        <div className="flex justify-between text-lg font-bold">
                          <span>Total Amount:</span>
                          <span>{formatCurrency(totalAmount)}</span>
                        </div>
                      </div>
                    </div>

                    <div className="pt-4 border-t">
                      <Button
                        type="submit"
                        variant="primary"
                        className="w-full"
                        disabled={createReturnMutation.isLoading || selectedItemIds.size === 0 || items.filter(i => i.quantity > 0).length === 0}
                        loading={createReturnMutation.isLoading}
                      >
                        Create Return
                      </Button>
                    </div>
                  </>
                ) : (
                  <p className="text-center py-8 text-gray-500 dark:text-gray-400 text-sm">
                    Search for an invoice to start creating a return
                  </p>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </form>
    </div>
  );
}
