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,
  Building2,
  Edit,
  Trash2,
  Save,
  X,
  Loader2,
  AlertCircle,
  User,
  Mail,
  Phone,
  Truck,
  FileText,
  DollarSign,
  Percent,
  Calendar,
  CreditCard,
  CheckCircle2,
  Clock,
  Wrench,
  Plus,
} from 'lucide-react';
import { customersApi, type Customer } from '../services/api/customers';
import { vehiclesApi } from '../services/api/vehicles';
import { serviceOrdersApi, type ServiceOrder } from '../services/api/serviceOrders';
import { ConfirmModal } from '../components/ui';
import { toast } from '../store/toastStore';
import type { Vehicle } from '../types';

interface EditCustomerForm {
  name: string;
  code: string;
  contact_name: string;
  contact_email: string;
  contact_phone: string;
  discount_labor_pct: number;
  discount_parts_pct: number;
  credit_days: number;
  credit_limit: number;
  notes: string;
  is_active: boolean;
}

const ORDER_STATUS_CONFIG: Record<string, { label: string; color: string }> = {
  received: { label: 'Recibido', color: 'bg-blue-100 text-blue-800' },
  diagnosing: { label: 'Diagnosticando', color: 'bg-purple-100 text-purple-800' },
  quoted: { label: 'Cotizado', color: 'bg-yellow-100 text-yellow-800' },
  approved: { label: 'Aprobado', color: 'bg-green-100 text-green-800' },
  in_repair: { label: 'En Reparacion', color: 'bg-orange-100 text-orange-800' },
  waiting_parts: { label: 'Esperando Partes', color: 'bg-red-100 text-red-800' },
  ready: { label: 'Listo', color: 'bg-emerald-100 text-emerald-800' },
  delivered: { label: 'Entregado', color: 'bg-gray-100 text-gray-800' },
  cancelled: { label: 'Cancelado', color: 'bg-gray-100 text-gray-500' },
};

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

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

  const customer: Customer | undefined = customerData?.data;

  // Fetch vehicles for this customer
  const { data: vehiclesData } = useQuery({
    queryKey: ['customer-vehicles', id],
    queryFn: () => vehiclesApi.list({ customerId: id }),
    enabled: !!id,
  });

  const vehicles: Vehicle[] = vehiclesData?.data?.data || [];

  // Fetch service orders for this customer
  const { data: ordersData } = useQuery({
    queryKey: ['customer-orders', id],
    queryFn: () => serviceOrdersApi.list({ customer_id: id, pageSize: 50 }),
    enabled: !!id,
  });

  const orders: ServiceOrder[] = ordersData?.data?.data || [];

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

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: (data: EditCustomerForm) => customersApi.update(id!, {
      name: data.name,
      code: data.code || undefined,
      contact_name: data.contact_name || undefined,
      contact_email: data.contact_email || undefined,
      contact_phone: data.contact_phone || undefined,
      discount_labor_pct: data.discount_labor_pct,
      discount_parts_pct: data.discount_parts_pct,
      credit_days: data.credit_days,
      credit_limit: data.credit_limit,
      notes: data.notes || undefined,
      is_active: data.is_active,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['customer', id] });
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      setIsEditing(false);
      toast.success('Cliente actualizado', 'Los cambios se guardaron correctamente');
    },
    onError: () => {
      toast.error('Error al guardar', 'No se pudieron guardar los cambios');
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: () => customersApi.delete(id!),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      toast.success('Cliente eliminado');
      navigate('/customers');
    },
    onError: () => {
      toast.error('Error al eliminar', 'No se pudo eliminar el cliente');
    },
  });

  const handleEdit = () => {
    if (customer) {
      reset({
        name: customer.name,
        code: customer.code || '',
        contact_name: customer.contact_name || '',
        contact_email: customer.contact_email || '',
        contact_phone: customer.contact_phone || '',
        discount_labor_pct: customer.discount_labor_pct,
        discount_parts_pct: customer.discount_parts_pct,
        credit_days: customer.credit_days,
        credit_limit: customer.credit_limit,
        notes: customer.notes || '',
        is_active: customer.is_active,
      });
      setIsEditing(true);
    }
  };

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

  const onSubmit = (data: EditCustomerForm) => {
    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 || !customer) {
    return (
      <div className="flex h-64 flex-col items-center justify-center text-gray-500">
        <AlertCircle className="mb-2 h-8 w-8" />
        <p>Cliente no encontrado</p>
        <Link to="/customers" className="mt-2 text-diesel-600 hover:text-diesel-700">
          Volver a clientes
        </Link>
      </div>
    );
  }

  // Calculate stats
  const totalSpent = orders
    .filter(o => o.status === 'delivered')
    .reduce((sum, o) => sum + o.grand_total, 0);
  const pendingOrders = orders.filter(o => !['delivered', 'cancelled'].includes(o.status)).length;
  const completedOrders = orders.filter(o => o.status === 'delivered').length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/customers"
            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">{customer.name}</h1>
              {customer.is_active ? (
                <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>
              )}
            </div>
            {customer.code && (
              <p className="text-sm text-gray-500">Codigo: {customer.code}</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>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <div className="rounded-xl border border-gray-200 bg-white p-4">
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <Truck className="h-4 w-4" />
            Vehiculos
          </div>
          <p className="mt-1 text-2xl font-bold text-gray-900">{vehicles.length}</p>
        </div>
        <div className="rounded-xl border border-gray-200 bg-white p-4">
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <FileText className="h-4 w-4" />
            Ordenes Activas
          </div>
          <p className="mt-1 text-2xl font-bold text-orange-600">{pendingOrders}</p>
        </div>
        <div className="rounded-xl border border-gray-200 bg-white p-4">
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <CheckCircle2 className="h-4 w-4" />
            Completadas
          </div>
          <p className="mt-1 text-2xl font-bold text-green-600">{completedOrders}</p>
        </div>
        <div className="rounded-xl border border-gray-200 bg-white p-4">
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <DollarSign className="h-4 w-4" />
            Total Facturado
          </div>
          <p className="mt-1 text-2xl font-bold text-diesel-600">
            ${totalSpent.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
          </p>
        </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">
          {/* Customer 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">
              <Building2 className="h-5 w-5 text-diesel-600" />
              Informacion del Cliente
            </h2>

            {isEditing ? (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Nombre / Razon Social</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>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Codigo</label>
                  <input
                    {...register('code')}
                    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="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="is_active"
                    {...register('is_active')}
                    className="h-4 w-4 rounded border-gray-300 text-diesel-600 focus:ring-diesel-500"
                  />
                  <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
                    Cliente Activo
                  </label>
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Nombre Contacto</label>
                  <input
                    {...register('contact_name')}
                    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">Telefono</label>
                  <input
                    {...register('contact_phone')}
                    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">Email</label>
                  <input
                    type="email"
                    {...register('contact_email')}
                    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">Notas</label>
                  <textarea
                    {...register('notes')}
                    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>
            ) : (
              <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                {customer.contact_name && (
                  <div className="flex items-start gap-2">
                    <User className="mt-0.5 h-4 w-4 text-gray-400" />
                    <div>
                      <p className="text-xs font-medium text-gray-500">Contacto</p>
                      <p className="text-sm text-gray-900">{customer.contact_name}</p>
                    </div>
                  </div>
                )}
                {customer.contact_phone && (
                  <div className="flex items-start gap-2">
                    <Phone className="mt-0.5 h-4 w-4 text-gray-400" />
                    <div>
                      <p className="text-xs font-medium text-gray-500">Telefono</p>
                      <p className="text-sm text-gray-900">{customer.contact_phone}</p>
                    </div>
                  </div>
                )}
                {customer.contact_email && (
                  <div className="flex items-start gap-2">
                    <Mail className="mt-0.5 h-4 w-4 text-gray-400" />
                    <div>
                      <p className="text-xs font-medium text-gray-500">Email</p>
                      <p className="text-sm text-gray-900">{customer.contact_email}</p>
                    </div>
                  </div>
                )}
                <div className="flex items-start gap-2">
                  <Calendar className="mt-0.5 h-4 w-4 text-gray-400" />
                  <div>
                    <p className="text-xs font-medium text-gray-500">Cliente desde</p>
                    <p className="text-sm text-gray-900">
                      {new Date(customer.created_at).toLocaleDateString('es-MX')}
                    </p>
                  </div>
                </div>
                {customer.notes && (
                  <div className="col-span-full">
                    <p className="text-xs font-medium text-gray-500">Notas</p>
                    <p className="text-sm text-gray-600">{customer.notes}</p>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Vehicles */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="flex items-center gap-2 text-lg font-semibold text-gray-900">
                <Truck className="h-5 w-5 text-diesel-600" />
                Vehiculos ({vehicles.length})
              </h2>
              <Link
                to={`/vehicles?customerId=${customer.id}`}
                className="flex items-center gap-2 rounded-lg bg-diesel-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-diesel-700"
              >
                <Plus className="h-4 w-4" />
                Agregar
              </Link>
            </div>

            {vehicles.length === 0 ? (
              <div className="flex h-24 flex-col items-center justify-center text-gray-400">
                <Truck className="mb-2 h-8 w-8" />
                <p className="text-sm">Sin vehiculos registrados</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {vehicles.slice(0, 5).map((vehicle) => (
                  <Link
                    key={vehicle.id}
                    to={`/vehicles/${vehicle.id}`}
                    className="-mx-2 flex items-center justify-between rounded-lg px-2 py-3 hover:bg-gray-50"
                  >
                    <div className="flex items-center gap-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-full bg-diesel-50">
                        <Truck className="h-5 w-5 text-diesel-600" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-900">
                          {vehicle.make} {vehicle.model} {vehicle.year}
                        </p>
                        <p className="text-xs text-gray-500">{vehicle.licensePlate}</p>
                      </div>
                    </div>
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                      vehicle.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
                    }`}>
                      {vehicle.status === 'active' ? 'Activo' : 'Inactivo'}
                    </span>
                  </Link>
                ))}
                {vehicles.length > 5 && (
                  <div className="pt-3 text-center">
                    <Link to={`/vehicles?customerId=${customer.id}`} className="text-sm text-diesel-600 hover:text-diesel-700">
                      Ver todos ({vehicles.length})
                    </Link>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Service History */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="flex items-center gap-2 text-lg font-semibold text-gray-900">
                <Wrench className="h-5 w-5 text-diesel-600" />
                Historial de Servicio
              </h2>
              <Link
                to={`/orders/new?customerId=${customer.id}`}
                className="flex items-center gap-2 rounded-lg bg-diesel-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-diesel-700"
              >
                <Plus className="h-4 w-4" />
                Nueva Orden
              </Link>
            </div>

            {orders.length === 0 ? (
              <div className="flex h-24 flex-col items-center justify-center text-gray-400">
                <FileText className="mb-2 h-8 w-8" />
                <p className="text-sm">Sin historial de servicio</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {orders.slice(0, 10).map((order) => {
                  const statusConfig = ORDER_STATUS_CONFIG[order.status] || ORDER_STATUS_CONFIG.received;
                  return (
                    <Link
                      key={order.id}
                      to={`/orders/${order.id}`}
                      className="-mx-2 flex items-center justify-between rounded-lg px-2 py-3 hover:bg-gray-50"
                    >
                      <div className="flex items-center gap-3">
                        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-diesel-50">
                          <Wrench className="h-5 w-5 text-diesel-600" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-900">{order.order_number}</p>
                          <p className="text-xs text-gray-500">{order.vehicle_info}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${statusConfig.color}`}>
                          {statusConfig.label}
                        </span>
                        <p className="mt-1 text-sm font-medium text-gray-900">
                          ${order.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                        </p>
                      </div>
                    </Link>
                  );
                })}
                {orders.length > 10 && (
                  <div className="pt-3 text-center">
                    <Link to={`/orders?customerId=${customer.id}`} className="text-sm text-diesel-600 hover:text-diesel-700">
                      Ver todas ({orders.length})
                    </Link>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Commercial Terms */}
          <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">
              <CreditCard className="h-5 w-5 text-diesel-600" />
              Condiciones Comerciales
            </h2>

            {isEditing ? (
              <div className="space-y-4">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Desc. Mano de Obra (%)</label>
                  <div className="relative">
                    <Percent 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('discount_labor_pct', { 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">Desc. Refacciones (%)</label>
                  <div className="relative">
                    <Percent 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('discount_parts_pct', { 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">Dias de Credito</label>
                  <input
                    type="number"
                    {...register('credit_days', { 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">Limite de Credito</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('credit_limit', { 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="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <Percent className="h-4 w-4" />
                    Desc. Mano de Obra
                  </span>
                  <span className="text-sm font-medium text-gray-900">{customer.discount_labor_pct}%</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <Percent className="h-4 w-4" />
                    Desc. Refacciones
                  </span>
                  <span className="text-sm font-medium text-gray-900">{customer.discount_parts_pct}%</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <Clock className="h-4 w-4" />
                    Dias de Credito
                  </span>
                  <span className="text-sm font-medium text-gray-900">{customer.credit_days} dias</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <CreditCard className="h-4 w-4" />
                    Limite de Credito
                  </span>
                  <span className="text-sm font-medium text-gray-900">
                    ${customer.credit_limit.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                  </span>
                </div>
              </div>
            )}
          </div>

          {/* Quick Stats */}
          <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" />
              Resumen Financiero
            </h2>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">Total Facturado</span>
                <span className="text-sm font-bold text-diesel-600">
                  ${totalSpent.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">Ticket Promedio</span>
                <span className="text-sm font-medium text-gray-900">
                  ${completedOrders > 0 ? (totalSpent / completedOrders).toLocaleString('es-MX', { minimumFractionDigits: 2 }) : '0.00'}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">Ordenes Totales</span>
                <span className="text-sm font-medium text-gray-900">{orders.length}</span>
              </div>
            </div>

            {/* Activity Indicator */}
            <div className="mt-4 border-t border-gray-100 pt-4">
              <div className="flex items-center gap-2">
                {pendingOrders > 0 ? (
                  <>
                    <Clock className="h-5 w-5 text-orange-500" />
                    <span className="text-sm font-medium text-orange-600">{pendingOrders} ordenes pendientes</span>
                  </>
                ) : (
                  <>
                    <CheckCircle2 className="h-5 w-5 text-green-500" />
                    <span className="text-sm font-medium text-green-600">Sin ordenes pendientes</span>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

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