import React, { useState, useEffect } from "react";
import { Customer } from "../src/services/customer.service";
import { customerService } from "../src/services/customer.service";
import {
  validateCustomerForm,
  validateCPForCNPJ,
  validateCEP,
  validatePhone,
} from "../lib/utils";
import ConfirmDialog from "./ConfirmDialog";

interface CreateCustomerDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (customer: Customer) => void;
}

const CreateCustomerDialog: React.FC<CreateCustomerDialogProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const [isAnimating, setIsAnimating] = useState(false);
  const [shouldRender, setShouldRender] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSearchingCustomer, setIsSearchingCustomer] = useState(false);
  const [showCustomerFoundDialog, setShowCustomerFoundDialog] = useState(false);
  const [foundCustomer, setFoundCustomer] = useState<Customer | null>(null);

  const [formData, setFormData] = useState({
    name: "",
    document: "",
    cellPhone: "",
    cep: "",
    address: "",
    number: "",
    city: "",
    state: "",
    complement: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
      setTimeout(() => setIsAnimating(true), 10);
      // Limpar formulário ao abrir
      setFormData({
        name: "",
        document: "",
        cellPhone: "",
        cep: "",
        address: "",
        number: "",
        city: "",
        state: "",
        complement: "",
      });
      setErrors({});
    } else {
      setIsAnimating(false);
      const timer = setTimeout(() => setShouldRender(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  if (!shouldRender) return null;

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    // Limpar erro do campo ao digitar
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  /**
   * Busca cliente por CPF/CNPJ ao sair do campo (blur)
   * Similar ao searchCustomerByDocument() do Angular
   */
  const handleSearchCustomerByDocument = async () => {
    const document = formData.document;

    // Remover caracteres não numéricos para a busca
    const cleanDocument = document.replace(/[^\d]/g, "");

    // Validar se tem pelo menos 11 dígitos (CPF mínimo) ou 14 (CNPJ)
    if (!cleanDocument || cleanDocument.length < 11) {
      return;
    }

    setIsSearchingCustomer(true);
    try {
      const customer = await customerService.getCustomerByCpf(cleanDocument);

      if (customer) {
        // Cliente encontrado - preencher formulário
        setFoundCustomer(customer);
        populateCustomerForm(customer);
        setShowCustomerFoundDialog(true);
      }
    } catch (error) {
      console.error("Erro ao buscar cliente por CPF/CNPJ:", error);
      // Não mostrar erro se o cliente não foi encontrado (é esperado para novos clientes)
    } finally {
      setIsSearchingCustomer(false);
    }
  };

  /**
   * Preenche o formulário com os dados do cliente encontrado
   * Similar ao populateCustomer() do Angular
   */
  const populateCustomerForm = (customer: Customer) => {
    setFormData({
      name: customer.name || "",
      document: customer.cpfCnpj || customer.document || "",
      cellPhone: customer.cellPhone || customer.phone || "",
      cep: customer.zipCode || customer.cep || "",
      address: customer.address || "",
      number: customer.addressNumber || customer.number || "",
      city: customer.city || "",
      state: customer.state || "",
      complement: customer.complement || "",
    });
  };

  /**
   * Fecha o dialog de cliente encontrado
   * O usuário pode continuar editando o formulário ou usar o cliente encontrado
   */
  const handleCloseCustomerFoundDialog = () => {
    setShowCustomerFoundDialog(false);
  };

  /**
   * Usa o cliente encontrado diretamente (sem editar)
   */
  const handleUseFoundCustomer = () => {
    setShowCustomerFoundDialog(false);
    if (foundCustomer) {
      // Chamar onSuccess com o cliente encontrado
      onSuccess(foundCustomer);
      onClose();
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validar formulário
    const validation = validateCustomerForm(formData);
    if (!validation.isValid) {
      setErrors(validation.errors);
      return;
    }

    setIsSubmitting(true);
    try {
      const newCustomer = await customerService.createCustomer(formData);
      if (newCustomer) {
        setIsAnimating(false);
        setTimeout(() => {
          onSuccess(newCustomer);
          onClose();
        }, 300);
      } else {
        setErrors({
          submit: "Não foi possível cadastrar o cliente. Tente novamente.",
        });
      }
    } catch (error: any) {
      setErrors({
        submit: error.message || "Erro ao cadastrar cliente. Tente novamente.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    setIsAnimating(false);
    setTimeout(() => {
      onClose();
      setFormData({
        name: "",
        document: "",
        cellPhone: "",
        cep: "",
        address: "",
        number: "",
        city: "",
        state: "",
        complement: "",
      });
      setErrors({});
    }, 300);
  };

  return (
    <div className="fixed inset-0 z-[200] flex items-center justify-center">
      {/* Overlay */}
      <div
        className={`absolute inset-0 bg-[#001f3f]/60 backdrop-blur-sm transition-opacity duration-300 ${
          isAnimating ? "opacity-100" : "opacity-0"
        }`}
        onClick={handleClose}
      ></div>

      {/* Dialog */}
      <div
        className={`relative bg-white rounded-3xl shadow-2xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden transform transition-all duration-300 ${
          isAnimating ? "scale-100 opacity-100" : "scale-95 opacity-0"
        }`}
      >
        {/* Header */}
        <div className="p-6 bg-[#002147] text-white rounded-t-3xl relative overflow-hidden">
          <div className="relative z-10">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-12 h-12 bg-green-500/20 rounded-2xl flex items-center justify-center">
                <svg
                  className="w-6 h-6 text-green-400"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2.5"
                    d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
                  />
                </svg>
              </div>
              <div className="flex-1">
                <h3 className="text-xl font-black">Novo Cliente</h3>
                <p className="text-xs text-green-400 font-bold uppercase tracking-wider mt-0.5">
                  Cadastro
                </p>
              </div>
              <button
                onClick={handleClose}
                className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center text-white hover:bg-white/20 transition-colors"
              >
                <svg
                  className="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2.5"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </div>
          </div>
          <div className="absolute right-[-10%] top-[-10%] w-32 h-32 bg-green-400/10 rounded-full blur-2xl"></div>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)] custom-scrollbar">
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Nome do Cliente */}
            <div>
              <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                Nome do Cliente *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleInputChange("name", e.target.value)}
                className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                  errors.name ? "border-red-500" : "border-slate-200"
                } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                placeholder="Digite o nome completo"
              />
              {errors.name && (
                <p className="text-red-500 text-xs mt-1">{errors.name}</p>
              )}
            </div>

            {/* CPF/CNPJ e Contato */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  CPF / CNPJ *
                </label>
                <div className="relative">
                  <input
                    type="text"
                    value={formData.document}
                    onChange={(e) =>
                      handleInputChange("document", e.target.value)
                    }
                    onBlur={handleSearchCustomerByDocument}
                    className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                      errors.document ? "border-red-500" : "border-slate-200"
                    } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                    placeholder="000.000.000-00"
                    disabled={isSearchingCustomer}
                  />
                  {isSearchingCustomer && (
                    <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                      <svg
                        className="animate-spin h-5 w-5 text-blue-500"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                      >
                        <circle
                          className="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          strokeWidth="4"
                        ></circle>
                        <path
                          className="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        ></path>
                      </svg>
                    </div>
                  )}
                </div>
                {errors.document && (
                  <p className="text-red-500 text-xs mt-1">{errors.document}</p>
                )}
              </div>
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  Contato *
                </label>
                <input
                  type="text"
                  value={formData.cellPhone}
                  onChange={(e) =>
                    handleInputChange("cellPhone", e.target.value)
                  }
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.cellPhone ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                  placeholder="(00) 00000-0000"
                />
                {errors.cellPhone && (
                  <p className="text-red-500 text-xs mt-1">
                    {errors.cellPhone}
                  </p>
                )}
              </div>
            </div>

            {/* CEP e Endereço */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  CEP *
                </label>
                <input
                  type="text"
                  value={formData.cep}
                  onChange={(e) => handleInputChange("cep", e.target.value)}
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.cep ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                  placeholder="00000-000"
                />
                {errors.cep && (
                  <p className="text-red-500 text-xs mt-1">{errors.cep}</p>
                )}
              </div>
              <div className="md:col-span-2">
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  Endereço *
                </label>
                <input
                  type="text"
                  value={formData.address}
                  onChange={(e) => handleInputChange("address", e.target.value)}
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.address ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                  placeholder="Rua, Avenida, etc."
                />
                {errors.address && (
                  <p className="text-red-500 text-xs mt-1">{errors.address}</p>
                )}
              </div>
            </div>

            {/* Número, Cidade e Estado */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  Número *
                </label>
                <input
                  type="text"
                  value={formData.number}
                  onChange={(e) => handleInputChange("number", e.target.value)}
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.number ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                  placeholder="123"
                />
                {errors.number && (
                  <p className="text-red-500 text-xs mt-1">{errors.number}</p>
                )}
              </div>
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  Cidade *
                </label>
                <input
                  type="text"
                  value={formData.city}
                  onChange={(e) => handleInputChange("city", e.target.value)}
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.city ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20`}
                  placeholder="Nome da cidade"
                />
                {errors.city && (
                  <p className="text-red-500 text-xs mt-1">{errors.city}</p>
                )}
              </div>
              <div>
                <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                  Estado *
                </label>
                <input
                  type="text"
                  value={formData.state}
                  onChange={(e) => handleInputChange("state", e.target.value)}
                  maxLength={2}
                  className={`w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border ${
                    errors.state ? "border-red-500" : "border-slate-200"
                  } focus:outline-none focus:ring-2 focus:ring-orange-500/20 uppercase`}
                  placeholder="PA"
                />
                {errors.state && (
                  <p className="text-red-500 text-xs mt-1">{errors.state}</p>
                )}
              </div>
            </div>

            {/* Complemento */}
            <div>
              <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
                Complemento
              </label>
              <input
                type="text"
                value={formData.complement}
                onChange={(e) =>
                  handleInputChange("complement", e.target.value)
                }
                className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20"
                placeholder="Apto, Bloco, etc. (opcional)"
              />
            </div>

            {/* Erro de submit */}
            {errors.submit && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-xl">
                <p className="text-red-600 text-sm font-medium">
                  {errors.submit}
                </p>
              </div>
            )}
          </form>
        </div>

        {/* Actions */}
        <div className="p-6 pt-05 flex gap-3 border-t border-slate-200">
          <button
            onClick={handleClose}
            className="flex-1 py-3 px-4 bg-slate-100 text-slate-600 font-bold uppercase text-xs tracking-wider rounded-xl hover:bg-slate-200 transition-all"
          >
            Cancelar
          </button>
          <button
            onClick={handleSubmit}
            disabled={isSubmitting}
            className="flex-1 py-3 px-4 text-white font-black uppercase text-xs tracking-wider rounded-xl transition-all shadow-lg bg-green-500 hover:bg-green-600 shadow-green-500/20 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isSubmitting ? "Cadastrando..." : "Cadastrar Cliente"}
          </button>
        </div>
      </div>

      {/* Dialog de Cliente Encontrado */}
      <ConfirmDialog
        isOpen={showCustomerFoundDialog}
        onClose={handleCloseCustomerFoundDialog}
        onConfirm={handleUseFoundCustomer}
        type="info"
        title="Cliente já cadastrado"
        message={`Cliente encontrado com este CPF/CNPJ!\n\nNome: ${
          foundCustomer?.name || ""
        }\n\nOs dados do formulário foram preenchidos automaticamente. Você pode editar os dados ou usar o cliente diretamente.`}
        confirmText="Usar Cliente"
        cancelText="Continuar Editando"
        showWarning={false}
      />
    </div>
  );
};

export default CreateCustomerDialog;
