/**
 * Inventory Item Detail Page
 * View details of a specific inventory item by UID
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation } from '@tanstack/react-query';
import { inventoryAPI } from '@/lib/api/inventory';
import { labelPrintingAPI } from '@/lib/api/labelPrinting';
import { Button, Card, CardHeader, CardTitle, CardContent, Badge, LoadingSpinner } from '@/components/ui';
import { ArrowLeft, Package, Barcode, QrCode, Copy, CheckCircle, XCircle, AlertTriangle, Printer } from 'lucide-react';
import toast from 'react-hot-toast';
import { useState } from 'react';

const STATUS_COLORS = {
  IN_STOCK: 'success',
  RESERVED: 'warning',
  SOLD: 'secondary',
  RETURNED: 'info',
  DAMAGED: 'danger',
  SCRAPPED: 'secondary',
};

const STATUS_LABELS = {
  IN_STOCK: 'In Stock',
  RESERVED: 'Reserved',
  SOLD: 'Sold',
  RETURNED: 'Returned',
  DAMAGED: 'Damaged',
  SCRAPPED: 'Scrapped',
};

export default function InventoryItemDetailPage() {
  const router = useRouter();
  const params = useParams();
  const uid = params.uid || '';
  const [copied, setCopied] = useState(false);

  // Fetch inventory item by UID
  const { data, isLoading, error } = useQuery({
    queryKey: ['inventory-item', uid],
    queryFn: async () => {
      const response = await inventoryAPI.getItemByUID(uid);
      return response?.data?.inventoryItem || response?.data?.item || response?.data || response;
    },
    enabled: !!uid,
  });

  const item = data;

  const copyToClipboard = async (text, label) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      toast.success(`${label} copied to clipboard`);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      toast.error('Failed to copy to clipboard');
    }
  };

  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 || !item) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <XCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
              <p className="text-red-600 dark:text-red-400 mb-4">
                {error?.message || 'Inventory item not found'}
              </p>
              <Button onClick={() => router.push('/inventory')} variant="outline">
                Back to Inventory
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 bg-gray-50 dark:bg-gray-950">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => {
              if (item.product_id) {
                router.push(`/inventory/items?product_id=${item.product_id}${item.variant_id ? `&variant_id=${item.variant_id}` : ''}`);
              } else {
                router.push('/inventory');
              }
            }}
            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">Inventory Item Details</h1>
            <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
              Unique Identifier: {item.uid}
            </p>
          </div>
        </div>
      </div>

      {/* Main Details */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Item Information */}
        <div className="lg:col-span-2 space-y-6">
          {/* Basic Information */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Package className="w-5 h-5" />
                Item Information
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {/* Product */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Product
                  </label>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">
                        {item.product?.name || 'Unknown Product'}
                      </p>
                      {item.product?.sku && (
                        <p className="text-sm text-gray-500 dark:text-gray-400 font-mono">
                          SKU: {item.product.sku}
                        </p>
                      )}
                    </div>
                    {item.product_id && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => router.push(`/products/${item.product_id}`)}
                      >
                        View Product
                      </Button>
                    )}
                  </div>
                </div>

                {/* Variant */}
                {item.variant && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Variant
                    </label>
                    <div>
                      <Badge variant="info" className="mb-2">Variant</Badge>
                      {item.variant.attributes && (
                        <div className="mt-2 space-y-1">
                          {Object.entries(item.variant.attributes).map(([key, value]) => (
                            <p key={key} className="text-sm text-gray-600 dark:text-gray-400">
                              <span className="font-medium">{key}:</span> {String(value)}
                            </p>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* UID */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Unique Identifier (UID)
                  </label>
                  <div className="flex items-center gap-2">
                    <code className="flex-1 text-sm font-mono bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded border border-gray-300 dark:border-gray-700">
                      {item.uid}
                    </code>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => copyToClipboard(item.uid, 'UID')}
                      className="flex items-center gap-2"
                    >
                      {copied ? <CheckCircle className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                      Copy
                    </Button>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    Unique identifier for this inventory item
                  </p>
                </div>

                {/* Barcode */}
                {item.barcode && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Barcode
                    </label>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 text-sm font-mono bg-gray-100 dark:bg-gray-800 px-3 py-2 rounded border border-gray-300 dark:border-gray-700 flex items-center gap-2">
                        <Barcode className="w-4 h-4 text-gray-400" />
                        {item.barcode}
                      </code>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => copyToClipboard(item.barcode, 'Barcode')}
                        className="flex items-center gap-2"
                      >
                        {copied ? <CheckCircle className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                        Copy
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Status & Source */}
          <Card>
            <CardHeader>
              <CardTitle>Status & Source</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Current Status
                  </label>
                  <Badge variant={STATUS_COLORS[item.status] || 'secondary'} className="text-base px-3 py-2">
                    {STATUS_LABELS[item.status] || item.status}
                  </Badge>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    {item.status === 'IN_STOCK' && 'Item is available for sale'}
                    {item.status === 'RESERVED' && 'Item is reserved for a pending sale'}
                    {item.status === 'SOLD' && 'Item has been sold'}
                    {item.status === 'RETURNED' && 'Item was returned by customer'}
                    {item.status === 'DAMAGED' && 'Item is damaged and cannot be sold'}
                    {item.status === 'SCRAPPED' && 'Item has been scrapped'}
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Source
                  </label>
                  <Badge variant="info" className="text-base px-3 py-2">
                    {item.source || 'Unknown'}
                  </Badge>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    {item.source === 'GRN' && 'Received via Goods Receipt Note'}
                    {item.source === 'PRODUCTION' && 'Produced in-house'}
                    {item.source === 'RETURN' && 'Returned from customer'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Timeline & Actions */}
        <div className="space-y-6">
          {/* Quick Info */}
          <Card>
            <CardHeader>
              <CardTitle>Quick Info</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <div>
                  <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
                    Created At
                  </label>
                  <p className="text-sm text-gray-900 dark:text-white">
                    {item.created_at
                      ? new Date(item.created_at).toLocaleString('en-US', {
                          year: 'numeric',
                          month: 'short',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })
                      : '-'}
                  </p>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
                    Last Updated
                  </label>
                  <p className="text-sm text-gray-900 dark:text-white">
                    {item.updated_at
                      ? new Date(item.updated_at).toLocaleString('en-US', {
                          year: 'numeric',
                          month: 'short',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })
                      : '-'}
                  </p>
                </div>
                {item.inventory_item_id && (
                  <div>
                    <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
                      Item ID
                    </label>
                    <code className="text-sm font-mono text-gray-900 dark:text-white">
                      #{item.id || item.inventory_item_id}
                    </code>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Actions */}
          <Card>
            <CardHeader>
              <CardTitle>Actions</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Button
                  variant="outline"
                  className="w-full justify-start"
                  onClick={() => {
                    if (item.product_id) {
                      router.push(`/products/${item.product_id}`);
                    }
                  }}
                  disabled={!item.product_id}
                >
                  View Product
                </Button>
                <Button
                  variant="outline"
                  className="w-full justify-start"
                  onClick={() => {
                    if (item.product_id) {
                      router.push(`/inventory/items?product_id=${item.product_id}`);
                    }
                  }}
                  disabled={!item.product_id}
                >
                  View All Items
                </Button>
                <Button
                  variant="outline"
                  className="w-full justify-start"
                  onClick={() => copyToClipboard(item.uid, 'UID')}
                >
                  <Copy className="w-4 h-4 mr-2" />
                  Copy UID
                </Button>
                {item.barcode && (
                  <Button
                    variant="outline"
                    className="w-full justify-start"
                    onClick={() => copyToClipboard(item.barcode, 'Barcode')}
                  >
                    <Barcode className="w-4 h-4 mr-2" />
                    Copy Barcode
                  </Button>
                )}
                <Button
                  variant="primary"
                  className="w-full justify-start"
                  onClick={() => {
                    // Default printer config (can be moved to settings or localStorage)
                    const printerConfig = {
                      method: 'network',
                      host: '192.168.1.100', // Default - should be configurable
                      port: 9100,
                    };
                    if (window.confirm('Print label for this inventory item? Make sure the printer is configured.')) {
                      labelPrintingAPI
                        .printInventoryItemLabel(item.id, printerConfig)
                        .then(() => {
                          toast.success('Label printed successfully!');
                        })
                        .catch((error) => {
                          const message = error?.response?.data?.message || error.message || 'Failed to print label';
                          toast.error(message);
                        });
                    }
                  }}
                  title="Print label for this inventory item"
                >
                  <Printer className="w-4 h-4 mr-2" />
                  Print Label
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* QR Code Preview (if available) */}
          {item.qr_code && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <QrCode className="w-5 h-5" />
                  QR Code
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex justify-center">
                  <img
                    src={item.qr_code}
                    alt={`QR Code for ${item.uid}`}
                    className="w-48 h-48 border border-gray-300 dark:border-gray-700 rounded-lg"
                  />
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-2 text-center">
                  Scan this QR code to view this item
                </p>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

