import { useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import {
  ArrowLeft,
  Package,
  Edit,
  Trash2,
  Save,
  X,
  Loader2,
  AlertCircle,
  DollarSign,
  Hash,
  Boxes,
  AlertTriangle,
  CheckCircle2,
  Barcode,
  MapPin,
  Tag,
  Settings,
  TrendingUp,
  Truck,
} from 'lucide-react';
import { partsApi } from '../services/api/parts';
import { ConfirmModal } from '../components/ui';
import { toast } from '../store/toastStore';
import type { Part } from '../types';

interface EditPartForm {
  sku: string;
  name: string;
  description: string;
  brand: string;
  manufacturer: string;
  cost: number;
  price: number;
  currentStock: number;
  minStock: number;
  maxStock: number;
  reorderPoint: number;
  unit: string;
  barcode: string;
  isActive: boolean;
}

export function InventoryDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [isEditing, setIsEditing] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // Fetch part data
  const { data: partData, isLoading, error } = useQuery({
    queryKey: ['part', id],
    queryFn: () => partsApi.getById(id!),
    enabled: !!id,
  });

  const part: Part | undefined = partData?.data;

  // Form setup
  const { register, handleSubmit, reset, formState: { isDirty } } = useForm<EditPartForm>();

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: (data: EditPartForm) => partsApi.update(id!, {
      sku: data.sku,
      name: data.name,
      description: data.description || undefined,
      brand: data.brand || undefined,
      manufacturer: data.manufacturer || undefined,
      cost: data.cost || undefined,
      price: data.price,
      currentStock: data.currentStock,
      minStock: data.minStock,
      maxStock: data.maxStock || undefined,
      reorderPoint: data.reorderPoint || undefined,
      unit: data.unit,
      barcode: data.barcode || undefined,
      isActive: data.isActive,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['part', id] });
      queryClient.invalidateQueries({ queryKey: ['parts'] });
      setIsEditing(false);
      toast.success('Refaccion actualizada', 'Los cambios se guardaron correctamente');
    },
    onError: () => {
      toast.error('Error al guardar', 'No se pudieron guardar los cambios');
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: () => partsApi.delete(id!),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['parts'] });
      toast.success('Refaccion eliminada');
      navigate('/inventory');
    },
    onError: () => {
      toast.error('Error al eliminar', 'No se pudo eliminar la refaccion');
    },
  });

  const handleEdit = () => {
    if (part) {
      reset({
        sku: part.sku,
        name: part.name,
        description: part.description || '',
        brand: part.brand || '',
        manufacturer: part.manufacturer || '',
        cost: part.cost || 0,
        price: part.price,
        currentStock: part.currentStock,
        minStock: part.minStock,
        maxStock: part.maxStock || 0,
        reorderPoint: part.reorderPoint || 0,
        unit: part.unit,
        barcode: part.barcode || '',
        isActive: part.isActive,
      });
      setIsEditing(true);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    reset();
  };

  const onSubmit = (data: EditPartForm) => {
    updateMutation.mutate(data);
  };

  if (isLoading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-diesel-600" />
      </div>
    );
  }

  if (error || !part) {
    return (
      <div className="flex h-64 flex-col items-center justify-center text-gray-500">
        <AlertCircle className="mb-2 h-8 w-8" />
        <p>Refaccion no encontrada</p>
        <Link to="/inventory" className="mt-2 text-diesel-600 hover:text-diesel-700">
          Volver a inventario
        </Link>
      </div>
    );
  }

  const isLowStock = part.currentStock <= part.minStock;
  const availableStock = part.currentStock - part.reservedStock;
  const stockPercentage = part.maxStock ? Math.round((part.currentStock / part.maxStock) * 100) : 0;
  const profit = part.price - (part.cost || 0);
  const profitMargin = part.cost ? Math.round((profit / part.cost) * 100) : 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/inventory"
            className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
          >
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-gray-900">{part.name}</h1>
              {part.isActive ? (
                <span className="rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800">
                  Activo
                </span>
              ) : (
                <span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
                  Inactivo
                </span>
              )}
              {isLowStock && (
                <span className="flex items-center gap-1 rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-800">
                  <AlertTriangle className="h-3 w-3" />
                  Stock Bajo
                </span>
              )}
            </div>
            <p className="text-sm text-gray-500">SKU: {part.sku}</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {!isEditing ? (
            <>
              <button
                onClick={handleEdit}
                className="flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                <Edit className="h-4 w-4" />
                Editar
              </button>
              <button
                onClick={() => setShowDeleteModal(true)}
                className="flex items-center gap-2 rounded-lg border border-red-300 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
              >
                <Trash2 className="h-4 w-4" />
                Eliminar
              </button>
            </>
          ) : (
            <>
              <button
                onClick={handleCancel}
                className="flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                <X className="h-4 w-4" />
                Cancelar
              </button>
              <button
                onClick={handleSubmit(onSubmit)}
                disabled={!isDirty || updateMutation.isPending}
                className="flex items-center gap-2 rounded-lg bg-diesel-600 px-4 py-2 text-sm font-medium text-white hover:bg-diesel-700 disabled:opacity-50"
              >
                {updateMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Save className="h-4 w-4" />
                )}
                Guardar
              </button>
            </>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Main Content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Part Info */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Package className="h-5 w-5 text-diesel-600" />
              Informacion de la Refaccion
            </h2>

            {isEditing ? (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">SKU</label>
                  <input
                    {...register('sku', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Codigo de Barras</label>
                  <input
                    {...register('barcode')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Nombre</label>
                  <input
                    {...register('name', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Descripcion</label>
                  <textarea
                    {...register('description')}
                    rows={2}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Marca</label>
                  <input
                    {...register('brand')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Fabricante</label>
                  <input
                    {...register('manufacturer')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Unidad</label>
                  <input
                    {...register('unit', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                    placeholder="pza, lt, kg"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="isActive"
                    {...register('isActive')}
                    className="h-4 w-4 rounded border-gray-300 text-diesel-600 focus:ring-diesel-500"
                  />
                  <label htmlFor="isActive" className="text-sm font-medium text-gray-700">
                    Activo
                  </label>
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                <div>
                  <p className="text-xs font-medium text-gray-500">SKU</p>
                  <p className="text-sm font-mono font-medium text-gray-900">{part.sku}</p>
                </div>
                {part.barcode && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Codigo de Barras</p>
                    <p className="text-sm font-mono text-gray-900">{part.barcode}</p>
                  </div>
                )}
                {part.brand && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Marca</p>
                    <p className="text-sm text-gray-900">{part.brand}</p>
                  </div>
                )}
                {part.manufacturer && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Fabricante</p>
                    <p className="text-sm text-gray-900">{part.manufacturer}</p>
                  </div>
                )}
                <div>
                  <p className="text-xs font-medium text-gray-500">Unidad</p>
                  <p className="text-sm text-gray-900">{part.unit}</p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500">Registrado</p>
                  <p className="text-sm text-gray-900">
                    {new Date(part.createdAt).toLocaleDateString('es-MX')}
                  </p>
                </div>
                {part.description && (
                  <div className="col-span-full">
                    <p className="text-xs font-medium text-gray-500">Descripcion</p>
                    <p className="text-sm text-gray-600">{part.description}</p>
                  </div>
                )}
                {part.compatibleEngines && part.compatibleEngines.length > 0 && (
                  <div className="col-span-full">
                    <p className="text-xs font-medium text-gray-500">Motores Compatibles</p>
                    <div className="mt-1 flex flex-wrap gap-1">
                      {part.compatibleEngines.map((engine, idx) => (
                        <span key={idx} className="rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-700">
                          {engine}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Pricing */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <DollarSign className="h-5 w-5 text-diesel-600" />
              Precios
            </h2>

            {isEditing ? (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Costo</label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                    <input
                      type="number"
                      step="0.01"
                      {...register('cost', { valueAsNumber: true })}
                      className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-3 text-sm focus:border-diesel-500 focus:outline-none"
                    />
                  </div>
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Precio de Venta</label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                    <input
                      type="number"
                      step="0.01"
                      {...register('price', { required: true, valueAsNumber: true })}
                      className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-3 text-sm focus:border-diesel-500 focus:outline-none"
                    />
                  </div>
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                <div>
                  <p className="text-xs font-medium text-gray-500">Costo</p>
                  <p className="text-lg font-semibold text-gray-900">
                    ${(part.cost || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500">Precio Venta</p>
                  <p className="text-lg font-semibold text-diesel-600">
                    ${part.price.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500">Utilidad</p>
                  <p className="text-lg font-semibold text-green-600">
                    ${profit.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500">Margen</p>
                  <p className="text-lg font-semibold text-gray-900">{profitMargin}%</p>
                </div>
              </div>
            )}
          </div>

          {/* Stock Management */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Boxes className="h-5 w-5 text-diesel-600" />
              Control de Inventario
            </h2>

            {isEditing ? (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Stock Actual</label>
                  <input
                    type="number"
                    {...register('currentStock', { required: true, valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Stock Minimo</label>
                  <input
                    type="number"
                    {...register('minStock', { required: true, valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Stock Maximo</label>
                  <input
                    type="number"
                    {...register('maxStock', { valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Punto de Reorden</label>
                  <input
                    type="number"
                    {...register('reorderPoint', { valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                {/* Stock Bar */}
                {part.maxStock && (
                  <div>
                    <div className="mb-2 flex items-center justify-between text-sm">
                      <span className="text-gray-600">Nivel de Stock</span>
                      <span className="font-medium text-gray-900">{stockPercentage}%</span>
                    </div>
                    <div className="h-3 w-full rounded-full bg-gray-200">
                      <div
                        className={`h-3 rounded-full transition-all ${
                          stockPercentage <= 25 ? 'bg-red-500' :
                          stockPercentage <= 50 ? 'bg-yellow-500' :
                          'bg-green-500'
                        }`}
                        style={{ width: `${Math.min(stockPercentage, 100)}%` }}
                      />
                    </div>
                  </div>
                )}

                <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                  <div className="rounded-lg bg-gray-50 p-3 text-center">
                    <p className="text-xs font-medium text-gray-500">Actual</p>
                    <p className={`text-2xl font-bold ${isLowStock ? 'text-red-600' : 'text-gray-900'}`}>
                      {part.currentStock}
                    </p>
                    <p className="text-xs text-gray-500">{part.unit}</p>
                  </div>
                  <div className="rounded-lg bg-blue-50 p-3 text-center">
                    <p className="text-xs font-medium text-blue-600">Reservado</p>
                    <p className="text-2xl font-bold text-blue-600">{part.reservedStock}</p>
                    <p className="text-xs text-blue-500">{part.unit}</p>
                  </div>
                  <div className="rounded-lg bg-green-50 p-3 text-center">
                    <p className="text-xs font-medium text-green-600">Disponible</p>
                    <p className="text-2xl font-bold text-green-600">{availableStock}</p>
                    <p className="text-xs text-green-500">{part.unit}</p>
                  </div>
                  <div className="rounded-lg bg-gray-50 p-3 text-center">
                    <p className="text-xs font-medium text-gray-500">Minimo</p>
                    <p className="text-2xl font-bold text-gray-900">{part.minStock}</p>
                    <p className="text-xs text-gray-500">{part.unit}</p>
                  </div>
                </div>

                {part.reorderPoint && (
                  <div className="flex items-center gap-2 rounded-lg bg-yellow-50 p-3 text-sm text-yellow-700">
                    <AlertTriangle className="h-4 w-4" />
                    Punto de reorden: {part.reorderPoint} {part.unit}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Quick Actions */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Settings className="h-5 w-5 text-diesel-600" />
              Acciones Rapidas
            </h2>

            <div className="space-y-2">
              <button className="flex w-full items-center gap-3 rounded-lg border border-gray-200 p-3 text-left text-sm hover:bg-gray-50">
                <TrendingUp className="h-5 w-5 text-green-600" />
                <div>
                  <p className="font-medium text-gray-900">Entrada de Stock</p>
                  <p className="text-xs text-gray-500">Registrar compra o devolucion</p>
                </div>
              </button>
              <button className="flex w-full items-center gap-3 rounded-lg border border-gray-200 p-3 text-left text-sm hover:bg-gray-50">
                <Truck className="h-5 w-5 text-orange-600" />
                <div>
                  <p className="font-medium text-gray-900">Salida de Stock</p>
                  <p className="text-xs text-gray-500">Registrar uso o ajuste</p>
                </div>
              </button>
              <button className="flex w-full items-center gap-3 rounded-lg border border-gray-200 p-3 text-left text-sm hover:bg-gray-50">
                <Barcode className="h-5 w-5 text-diesel-600" />
                <div>
                  <p className="font-medium text-gray-900">Imprimir Etiqueta</p>
                  <p className="text-xs text-gray-500">Generar codigo de barras</p>
                </div>
              </button>
            </div>
          </div>

          {/* Stats Summary */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Hash className="h-5 w-5 text-diesel-600" />
              Resumen
            </h2>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <Tag className="h-4 w-4" />
                  Valor en Stock
                </span>
                <span className="text-sm font-medium text-gray-900">
                  ${(part.currentStock * part.price).toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <DollarSign className="h-4 w-4" />
                  Costo en Stock
                </span>
                <span className="text-sm font-medium text-gray-900">
                  ${(part.currentStock * (part.cost || 0)).toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>
              {part.maxStock && (
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <Boxes className="h-4 w-4" />
                    Stock Maximo
                  </span>
                  <span className="text-sm font-medium text-gray-900">{part.maxStock} {part.unit}</span>
                </div>
              )}
              {part.locationId && (
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <MapPin className="h-4 w-4" />
                    Ubicacion
                  </span>
                  <span className="text-sm font-medium text-gray-900">{part.locationId}</span>
                </div>
              )}
            </div>

            {/* Status Indicator */}
            <div className="mt-4 border-t border-gray-100 pt-4">
              <div className="flex items-center gap-2">
                {isLowStock ? (
                  <>
                    <AlertTriangle className="h-5 w-5 text-red-500" />
                    <span className="text-sm font-medium text-red-600">Requiere reabastecimiento</span>
                  </>
                ) : (
                  <>
                    <CheckCircle2 className="h-5 w-5 text-green-500" />
                    <span className="text-sm font-medium text-green-600">Stock saludable</span>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      <ConfirmModal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        onConfirm={() => deleteMutation.mutate()}
        title="Eliminar Refaccion"
        message={`¿Estas seguro de eliminar "${part.name}" (${part.sku})? Esta accion no se puede deshacer.`}
        confirmText="Eliminar"
        variant="danger"
        isLoading={deleteMutation.isPending}
      />
    </div>
  );
}
