/**
 * Inventory Reconciliation Page
 * Check and fix inventory discrepancies between quantity-based and UID-based inventory
 */

'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { inventoryAPI } from '@/lib/api/inventory';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner } from '@/components/ui';
import { RefreshCw, AlertTriangle, CheckCircle, XCircle, Database } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatNumber } from '@/lib/utils/format';

export default function ReconciliationPage() {
  const queryClient = useQueryClient();
  const [productId, setProductId] = useState(null);

  // Fetch reconciliation report
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['inventory-reconciliation', productId],
    queryFn: async () => {
      const response = await inventoryAPI.getReconciliationReport(productId);
      return response.data || response;
    },
  });

  // Auto-reconcile mutation
  const reconcileMutation = useMutation({
    mutationFn: async (productId = null) => {
      return inventoryAPI.autoReconcile(productId);
    },
    onSuccess: (response) => {
      const result = response.data || response;
      const fixed = result.fixed?.length || 0;
      const errors = result.errors?.length || 0;
      
      if (fixed > 0) {
        toast.success(`Successfully reconciled ${fixed} inventory item(s)`);
      }
      if (errors > 0) {
        toast.error(`${errors} error(s) occurred during reconciliation`);
      }
      if (fixed === 0 && errors === 0) {
        toast.success('No discrepancies found to reconcile');
      }

      // Refetch reconciliation report
      queryClient.invalidateQueries({ queryKey: ['inventory-reconciliation'] });
      // Also invalidate inventory list
      queryClient.invalidateQueries({ queryKey: ['inventory'] });
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to reconcile inventory');
    },
  });

  const discrepancies = data?.discrepancies || [];
  const summary = data?.summary || {};

  const handleReconcile = () => {
    if (discrepancies.length === 0) {
      toast.error('No discrepancies to reconcile');
      return;
    }

    if (confirm(`Are you sure you want to reconcile ${discrepancies.length} discrepancy/discrepancies? This will update Inventory quantities to match UID counts.`)) {
      reconcileMutation.mutate(productId);
    }
  };

  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">Inventory Reconciliation</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Identify and fix discrepancies between quantity-based and UID-based inventory
          </p>
        </div>
        <div className="flex gap-3">
          <Button
            variant="outline"
            onClick={() => refetch()}
            disabled={isLoading}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
          <Button
            onClick={handleReconcile}
            disabled={isLoading || discrepancies.length === 0 || reconcileMutation.isPending}
          >
            {reconcileMutation.isPending ? (
              <>
                <LoadingSpinner size="sm" className="mr-2" />
                Reconciling...
              </>
            ) : (
              <>
                <CheckCircle className="w-4 h-4 mr-2" />
                Auto-Reconcile All
              </>
            )}
          </Button>
        </div>
      </div>

      {/* Summary Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="w-5 h-5" />
            Reconciliation Summary
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center py-8">
              <LoadingSpinner size="lg" />
            </div>
          ) : error ? (
            <div className="text-center py-8 text-red-600 dark:text-red-400">
              <XCircle className="w-12 h-12 mx-auto mb-2" />
              <p>Error loading reconciliation data. Please try again.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                <div className="text-sm font-medium text-blue-700 dark:text-blue-300">Total Discrepancies</div>
                <div className="mt-2 text-3xl font-bold text-blue-900 dark:text-blue-100">
                  {data?.total_discrepancies || 0}
                </div>
              </div>
              <div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
                <div className="text-sm font-medium text-yellow-700 dark:text-yellow-300">Quantity Higher</div>
                <div className="mt-2 text-3xl font-bold text-yellow-900 dark:text-yellow-100">
                  {summary.quantity_higher || 0}
                </div>
                <div className="mt-1 text-xs text-yellow-600 dark:text-yellow-400">
                  Inventory.quantity &gt; UID count
                </div>
              </div>
              <div className="p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg border border-orange-200 dark:border-orange-800">
                <div className="text-sm font-medium text-orange-700 dark:text-orange-300">UID Higher</div>
                <div className="mt-2 text-3xl font-bold text-orange-900 dark:text-orange-100">
                  {summary.uid_higher || 0}
                </div>
                <div className="mt-1 text-xs text-orange-600 dark:text-orange-400">
                  UID count &gt; Inventory.quantity
                </div>
              </div>
              <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
                <div className="text-sm font-medium text-red-700 dark:text-red-300">Total Difference</div>
                <div className="mt-2 text-3xl font-bold text-red-900 dark:text-red-100">
                  {formatNumber(summary.total_difference || 0, 0)}
                </div>
                <div className="mt-1 text-xs text-red-600 dark:text-red-400">
                  Units out of sync
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Discrepancies Table */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-yellow-500" />
            Discrepancies Found
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center py-12">
              <LoadingSpinner size="lg" />
            </div>
          ) : discrepancies.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <CheckCircle className="w-12 h-12 mx-auto mb-4 text-green-500" />
              <p className="text-lg font-medium">No discrepancies found!</p>
              <p className="text-sm mt-1">Your inventory is in sync.</p>
            </div>
          ) : (
            <>
              <div className="mb-4 text-sm text-gray-600 dark:text-gray-400">
                <p>
                  <strong>Note:</strong> Auto-reconciliation will update Inventory.quantity to match the UID count 
                  (using InventoryItem records as the source of truth).
                </p>
              </div>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead>Variant</TableHead>
                    <TableHead align="right">Quantity-Based</TableHead>
                    <TableHead align="right">UID-Based</TableHead>
                    <TableHead align="right">Difference</TableHead>
                    <TableHead>Type</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {discrepancies.map((item) => (
                    <TableRow key={item.inventory_id}>
                      <TableCell>
                        <div>
                          <div className="font-medium">
                            {item.product_name || 'Unknown Product'}
                          </div>
                          {item.product_sku && (
                            <div className="text-xs text-gray-500 font-mono">
                              SKU: {item.product_sku}
                            </div>
                          )}
                          <div className="text-xs text-gray-500">
                            Inventory ID: {item.inventory_id}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {item.variant_id ? (
                          <Badge variant="info">Variant {item.variant_id}</Badge>
                        ) : (
                          <span className="text-gray-400">Standard</span>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <span className="font-medium">{formatNumber(item.quantity_based, 0)}</span>
                      </TableCell>
                      <TableCell align="right">
                        <span className="font-medium">{formatNumber(item.uid_based, 0)}</span>
                      </TableCell>
                      <TableCell align="right">
                        <Badge variant={item.discrepancy_type === 'QUANTITY_HIGHER' ? 'warning' : 'danger'}>
                          {item.discrepancy_type === 'QUANTITY_HIGHER' ? '+' : '-'}
                          {formatNumber(item.difference, 0)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={item.discrepancy_type === 'QUANTITY_HIGHER' ? 'warning' : 'danger'}>
                          {item.discrepancy_type === 'QUANTITY_HIGHER' ? 'Quantity Higher' : 'UID Higher'}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </>
          )}
        </CardContent>
      </Card>

      {/* Info Card */}
      {discrepancies.length > 0 && (
        <Card className="border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20">
          <CardContent className="pt-6">
            <div className="flex gap-3">
              <AlertTriangle className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-800 dark:text-blue-200">
                <p className="font-medium mb-2">About Auto-Reconciliation:</p>
                <ul className="list-disc list-inside space-y-1 text-blue-700 dark:text-blue-300">
                  <li>This will sync Inventory.quantity to match the count of IN_STOCK InventoryItem records</li>
                  <li>UID-based inventory (InventoryItem records) is used as the source of truth</li>
                  <li>This operation is safe and doesn't delete any data</li>
                  <li>All changes are logged in the system audit trail</li>
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

