import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  Building2,
  Plus,
  Search,
  Edit2,
  Trash2,
  X,
  Loader2,
  AlertCircle,
  Phone,
  Mail,
  Truck,
  CreditCard,
  ChevronRight,
} from 'lucide-react';
import { customersApi } from '../services/api/customers';
import type { Customer, CustomerFilters } from '../services/api/customers';

const customerSchema = z.object({
  name: z.string().min(1, 'Nombre requerido'),
  code: z.string().optional(),
  contact_name: z.string().optional(),
  contact_email: z.string().email('Email invalido').optional().or(z.literal('')),
  contact_phone: z.string().optional(),
  discount_labor_pct: z.number().min(0).max(100).optional(),
  discount_parts_pct: z.number().min(0).max(100).optional(),
  credit_days: z.number().min(0).optional(),
  credit_limit: z.number().min(0).optional(),
  notes: z.string().optional(),
});

type CustomerForm = z.infer<typeof customerSchema>;

export function CustomersPage() {
  const queryClient = useQueryClient();
  const [filters, setFilters] = useState<CustomerFilters>({ page: 1, pageSize: 20 });
  const [searchTerm, setSearchTerm] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<CustomerForm>({
    resolver: zodResolver(customerSchema),
    defaultValues: {
      discount_labor_pct: 0,
      discount_parts_pct: 0,
      credit_days: 0,
      credit_limit: 0,
    },
  });

  // Fetch customers
  const { data, isLoading, error } = useQuery({
    queryKey: ['customers', filters],
    queryFn: () => customersApi.list(filters),
  });

  // Create mutation
  const createMutation = useMutation({
    mutationFn: (data: CustomerForm) => customersApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      handleCloseModal();
    },
  });

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<CustomerForm> }) =>
      customersApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      handleCloseModal();
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: (id: string) => customersApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['customers'] });
    },
  });

  const customers = data?.data?.data || [];

  const handleSearch = () => {
    setFilters({ ...filters, search: searchTerm, page: 1 });
  };

  const handleOpenCreate = () => {
    setEditingCustomer(null);
    reset({
      discount_labor_pct: 0,
      discount_parts_pct: 0,
      credit_days: 0,
      credit_limit: 0,
    });
    setShowModal(true);
  };

  const handleOpenEdit = (customer: Customer) => {
    setEditingCustomer(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,
    });
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setEditingCustomer(null);
    reset();
  };

  const onSubmit = (data: CustomerForm) => {
    // Clean empty email
    const cleanData = {
      ...data,
      contact_email: data.contact_email || undefined,
    };

    if (editingCustomer) {
      updateMutation.mutate({ id: editingCustomer.id, data: cleanData });
    } else {
      createMutation.mutate(cleanData);
    }
  };

  const handleDelete = (customer: Customer) => {
    if (confirm(`Eliminar cliente ${customer.name}?`)) {
      deleteMutation.mutate(customer.id);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Clientes</h1>
          <p className="text-sm text-gray-500">Gestiona los clientes y flotas</p>
        </div>
        <button
          onClick={handleOpenCreate}
          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"
        >
          <Plus className="h-4 w-4" />
          Nuevo Cliente
        </button>
      </div>

      {/* Search */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            placeholder="Buscar por nombre, codigo..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 text-sm focus:border-diesel-500 focus:outline-none focus:ring-1 focus:ring-diesel-500"
          />
        </div>
        <button
          onClick={handleSearch}
          className="rounded-lg bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200"
        >
          Buscar
        </button>
      </div>

      {/* Grid */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        {isLoading ? (
          <div className="col-span-full flex h-64 items-center justify-center">
            <Loader2 className="h-8 w-8 animate-spin text-diesel-600" />
          </div>
        ) : error ? (
          <div className="col-span-full flex h-64 flex-col items-center justify-center text-gray-500">
            <AlertCircle className="mb-2 h-8 w-8" />
            <p>Error al cargar clientes</p>
          </div>
        ) : customers.length === 0 ? (
          <div className="col-span-full flex h-64 flex-col items-center justify-center text-gray-500">
            <Building2 className="mb-2 h-8 w-8" />
            <p>No hay clientes registrados</p>
            <button
              onClick={handleOpenCreate}
              className="mt-2 text-sm text-diesel-600 hover:text-diesel-700"
            >
              Registrar primer cliente
            </button>
          </div>
        ) : (
          customers.map((customer: Customer) => (
            <div
              key={customer.id}
              className="rounded-xl border border-gray-200 bg-white p-5 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start justify-between">
                <Link to={`/customers/${customer.id}`} className="flex items-center gap-3 hover:opacity-80">
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-diesel-100">
                    <Building2 className="h-6 w-6 text-diesel-600" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900">{customer.name}</h3>
                    {customer.code && (
                      <p className="text-sm text-gray-500">{customer.code}</p>
                    )}
                  </div>
                </Link>
                <div className="flex gap-1">
                  <button
                    onClick={() => handleOpenEdit(customer)}
                    className="rounded p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
                  >
                    <Edit2 className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(customer)}
                    className="rounded p-1.5 text-gray-400 hover:bg-red-50 hover:text-red-600"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>

              <div className="mt-4 space-y-2">
                {customer.contact_name && (
                  <p className="text-sm text-gray-600">{customer.contact_name}</p>
                )}
                {customer.contact_phone && (
                  <p className="flex items-center gap-2 text-sm text-gray-500">
                    <Phone className="h-3.5 w-3.5" />
                    {customer.contact_phone}
                  </p>
                )}
                {customer.contact_email && (
                  <p className="flex items-center gap-2 text-sm text-gray-500">
                    <Mail className="h-3.5 w-3.5" />
                    {customer.contact_email}
                  </p>
                )}
              </div>

              <div className="mt-4 flex items-center justify-between border-t border-gray-100 pt-4">
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-1 text-sm text-gray-500">
                    <Truck className="h-4 w-4" />
                    <span>{customer.vehicle_count}</span>
                  </div>
                  {customer.credit_limit > 0 && (
                    <div className="flex items-center gap-1 text-sm text-gray-500">
                      <CreditCard className="h-4 w-4" />
                      <span>${customer.credit_limit.toLocaleString('es-MX')}</span>
                    </div>
                  )}
                </div>
                <Link
                  to={`/customers/${customer.id}`}
                  className="flex items-center gap-1 text-sm font-medium text-diesel-600 hover:text-diesel-700"
                >
                  Ver detalle
                  <ChevronRight className="h-4 w-4" />
                </Link>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Pagination */}
      {data?.data && customers.length > 0 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Pagina {data.data.page} de {data.data.totalPages}
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => setFilters({ ...filters, page: (filters.page || 1) - 1 })}
              disabled={(filters.page || 1) <= 1}
              className="rounded-lg border border-gray-300 px-3 py-1 text-sm disabled:opacity-50"
            >
              Anterior
            </button>
            <button
              onClick={() => setFilters({ ...filters, page: (filters.page || 1) + 1 })}
              disabled={(filters.page || 1) >= data.data.totalPages}
              className="rounded-lg border border-gray-300 px-3 py-1 text-sm disabled:opacity-50"
            >
              Siguiente
            </button>
          </div>
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-900">
                {editingCustomer ? 'Editar Cliente' : 'Nuevo Cliente'}
              </h2>
              <button onClick={handleCloseModal} className="text-gray-400 hover:text-gray-600">
                <X className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">
                    Nombre de Empresa *
                  </label>
                  <input
                    {...register('name')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                    placeholder="Transportes del Norte SA"
                  />
                  {errors.name && <p className="mt-1 text-sm text-red-600">{errors.name.message}</p>}
                </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"
                    placeholder="TDN-001"
                  />
                </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"
                    placeholder="Juan Perez"
                  />
                </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"
                    placeholder="81 1234 5678"
                  />
                </div>

                <div>
                  <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"
                    placeholder="contacto@empresa.com"
                  />
                  {errors.contact_email && (
                    <p className="mt-1 text-sm text-red-600">{errors.contact_email.message}</p>
                  )}
                </div>
              </div>

              <div className="border-t border-gray-200 pt-4">
                <h3 className="mb-3 text-sm font-medium text-gray-700">Condiciones Comerciales</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">
                      Descuento Mano de Obra (%)
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      {...register('discount_labor_pct', { 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">
                      Descuento Refacciones (%)
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      {...register('discount_parts_pct', { 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">
                      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>
                    <input
                      type="number"
                      {...register('credit_limit', { 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>

              <div>
                <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 className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={handleCloseModal}
                  className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={createMutation.isPending || 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"
                >
                  {(createMutation.isPending || updateMutation.isPending) && (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  )}
                  {editingCustomer ? 'Guardar Cambios' : 'Crear Cliente'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
