"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Building2, Loader2, MapPin, Search, User, X } from "lucide-react";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { fetchAddressByCep } from "@/services/customer-service";
import { CreateCustomerDTO, Customer, CustomerStatus, CustomerType } from "@/types/customer";
import { customerSchema, CustomerFormValues } from "@/validators/customer";

interface CustomerFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: CreateCustomerDTO) => Promise<void>;
  customerToEdit?: Customer | null;
  isSaving?: boolean;
}

export function CustomerFormModal({
  isOpen,
  onClose,
  onSubmit,
  customerToEdit,
  isSaving = false,
}: CustomerFormModalProps) {
  const [isSearchingCep, setIsSearchingCep] = useState(false);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<CustomerFormValues>({
    resolver: zodResolver(customerSchema),
    defaultValues: {
      type: "COMPANY",
      name: "",
      document: "",
      email: "",
      phone: "",
      mobile: "",
      contactName: "",
      creditLimit: 0,
      status: "ACTIVE",
      notes: "",
      zipCode: "",
      street: "",
      number: "",
      complement: "",
      district: "",
      city: "",
      state: "",
    },
  });

  const [creditLimitDisplay, setCreditLimitDisplay] = useState("");

  const formatCep = (value: string) => {
    const clean = value.replace(/\D/g, "");
    return clean.slice(0, 8).replace(/(\d{5})(\d)/, "$1-$2");
  };

  const formatPhone = (value: string) => {
    const clean = value.replace(/\D/g, "");
    return clean.slice(0, 10).replace(/(\d{2})(\d)/, "($1) $2").replace(/(\d{4})(\d)/, "$1-$2");
  };

  const formatMobile = (value: string) => {
    const clean = value.replace(/\D/g, "");
    return clean.slice(0, 11).replace(/(\d{2})(\d)/, "($1) $2").replace(/(\d{5})(\d)/, "$1-$2");
  };

  const formatCurrency = (value: string) => {
    const clean = value.replace(/\D/g, "");
    if (!clean) return "";
    const num = parseInt(clean, 10) / 100;
    return new Intl.NumberFormat("pt-BR", {
      style: "currency",
      currency: "BRL",
    }).format(num);
  };

  const parseCurrencyToNumber = (value: string): number => {
    const clean = value.replace(/\D/g, "");
    if (!clean) return 0;
    return parseInt(clean, 10) / 100;
  };

  const selectedType = watch("type");
  const zipCodeValue = watch("zipCode");

  useEffect(() => {
    if (customerToEdit) {
      const formattedDoc = formatDocument(customerToEdit.document, customerToEdit.type);
      const formattedPhone = customerToEdit.phone ? formatPhone(customerToEdit.phone) : "";
      const formattedMobile = customerToEdit.mobile ? formatMobile(customerToEdit.mobile) : "";
      const formattedCep = customerToEdit.zipCode ? formatCep(customerToEdit.zipCode) : "";
      const initialLimit = Number(customerToEdit.creditLimit) || 0;

      setCreditLimitDisplay(
        new Intl.NumberFormat("pt-BR", {
          style: "currency",
          currency: "BRL",
        }).format(initialLimit)
      );

      reset({
        type: customerToEdit.type,
        name: customerToEdit.name,
        document: formattedDoc,
        email: customerToEdit.email || "",
        phone: formattedPhone,
        mobile: formattedMobile,
        contactName: customerToEdit.contactName || "",
        creditLimit: initialLimit,
        status: customerToEdit.status,
        notes: customerToEdit.notes || "",
        zipCode: formattedCep,
        street: customerToEdit.street || "",
        number: customerToEdit.number || "",
        complement: customerToEdit.complement || "",
        district: customerToEdit.district || "",
        city: customerToEdit.city || "",
        state: customerToEdit.state || "",
      });
    } else {
      setCreditLimitDisplay("");
      reset({
        type: "COMPANY",
        name: "",
        document: "",
        email: "",
        phone: "",
        mobile: "",
        contactName: "",
        creditLimit: 0,
        status: "ACTIVE",
        notes: "",
        zipCode: "",
        street: "",
        number: "",
        complement: "",
        district: "",
        city: "",
        state: "",
      });
    }
  }, [customerToEdit, reset, isOpen]);

  const handleCepSearch = async () => {
    if (!zipCodeValue) return;
    setIsSearchingCep(true);
    try {
      const address = await fetchAddressByCep(zipCodeValue);
      if (address) {
        setValue("zipCode", address.zipCode);
        setValue("street", address.street);
        setValue("district", address.district);
        setValue("city", address.city);
        setValue("state", address.state);
      }
    } finally {
      setIsSearchingCep(false);
    }
  };

  const formatDocument = (value: string, type: CustomerType) => {
    const clean = value.replace(/\D/g, "");
    if (type === "INDIVIDUAL") {
      return clean
        .slice(0, 11)
        .replace(/(\d{3})(\d)/, "$1.$2")
        .replace(/(\d{3})(\d)/, "$1.$2")
        .replace(/(\d{3})(\d{1,2})$/, "$1-$2");
    }
    return clean
      .slice(0, 14)
      .replace(/^(\d{2})(\d)/, "$1.$2")
      .replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
      .replace(/\.(\d{3})(\d)/, ".$1/$2")
      .replace(/(\d{4})(\d)/, "$1-$2");
  };

  const handleDocumentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatDocument(e.target.value, selectedType);
    setValue("document", formatted, { shouldValidate: true });
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatPhone(e.target.value);
    setValue("phone", formatted, { shouldValidate: true });
  };

  const handleMobileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatMobile(e.target.value);
    setValue("mobile", formatted, { shouldValidate: true });
  };

  const handleCepChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatCep(e.target.value);
    setValue("zipCode", formatted, { shouldValidate: true });
  };

  const handleCreditLimitChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatCurrency(e.target.value);
    setCreditLimitDisplay(formatted);
    const numericValue = parseCurrencyToNumber(formatted);
    setValue("creditLimit", numericValue, { shouldValidate: true });
  };

  const onFormSubmit = async (values: CustomerFormValues) => {
    await onSubmit(values);
    onClose();
  };

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!isOpen || !mounted) return null;

  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs transition-all">
      <Card className="w-full max-w-3xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden p-0">
        {/* Header Fixo no Topo */}
        <div className="flex items-center justify-between border-b px-6 py-4 bg-background shrink-0">
          <div>
            <h2 className="text-xl font-bold flex items-center gap-2">
              <User className="h-5 w-5 text-primary" />
              {customerToEdit ? "Editar Cliente" : "Novo Cliente"}
            </h2>
            <p className="text-sm text-muted-foreground">
              {customerToEdit
                ? "Atualize as informações cadastrais do cliente."
                : "Preencha os dados para cadastrar um novo cliente."}
            </p>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        <form onSubmit={handleSubmit(onFormSubmit)} className="flex-1 flex flex-col overflow-hidden min-h-0">
          {/* Corpo Rolável */}
          <div className="flex-1 overflow-y-auto px-6 py-5 space-y-6">
            {/* Tipo de Pessoa */}
          <div>
            <label className="mb-2 block text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Tipo de Pessoa
            </label>
            <div className="grid grid-cols-2 gap-3">
              <button
                type="button"
                onClick={() => {
                  setValue("type", "COMPANY");
                  setValue("document", "");
                }}
                className={`flex items-center justify-center gap-2 rounded-lg border p-3 font-medium transition ${
                  selectedType === "COMPANY"
                    ? "border-primary bg-primary/10 text-primary font-semibold"
                    : "hover:bg-muted"
                }`}
              >
                <Building2 className="h-4 w-4" /> Pessoa Jurídica (PJ)
              </button>
              <button
                type="button"
                onClick={() => {
                  setValue("type", "INDIVIDUAL");
                  setValue("document", "");
                }}
                className={`flex items-center justify-center gap-2 rounded-lg border p-3 font-medium transition ${
                  selectedType === "INDIVIDUAL"
                    ? "border-primary bg-primary/10 text-primary font-semibold"
                    : "hover:bg-muted"
                }`}
              >
                <User className="h-4 w-4" /> Pessoa Física (PF)
              </button>
            </div>
          </div>

          {/* Dados Principais */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
              Informações Cadastrais
            </h3>
            <div className="grid gap-4 md:grid-cols-2">
              <div>
                <label className="mb-1 block text-sm font-medium">
                  {selectedType === "COMPANY" ? "Razão Social *" : "Nome Completo *"}
                </label>
                <Input
                  {...register("name")}
                  placeholder={
                    selectedType === "COMPANY"
                      ? "Ex: Construtora Atlas LTDA"
                      : "Ex: João da Silva"
                  }
                />
                {errors.name && (
                  <p className="mt-1 text-xs text-rose-500">{errors.name.message}</p>
                )}
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">
                  {selectedType === "COMPANY" ? "CNPJ *" : "CPF *"}
                </label>
                <Input
                  {...register("document")}
                  onChange={handleDocumentChange}
                  placeholder={
                    selectedType === "COMPANY"
                      ? "00.000.000/0001-00"
                      : "000.000.000-00"
                  }
                />
                {errors.document && (
                  <p className="mt-1 text-xs text-rose-500">{errors.document.message}</p>
                )}
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">
                  {selectedType === "COMPANY" ? "Nome do Contato" : "Apelido / Contato"}
                </label>
                <Input
                  {...register("contactName")}
                  placeholder="Ex: Eng. Roberto / Financeiro"
                />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">E-mail</label>
                <Input
                  {...register("email")}
                  type="email"
                  placeholder="contato@empresa.com.br"
                />
                {errors.email && (
                  <p className="mt-1 text-xs text-rose-500">{errors.email.message}</p>
                )}
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Telefone Fixo</label>
                <Input
                  {...register("phone")}
                  onChange={handlePhoneChange}
                  placeholder="(00) 0000-0000"
                />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Celular / WhatsApp</label>
                <Input
                  {...register("mobile")}
                  onChange={handleMobileChange}
                  placeholder="(00) 90000-0000"
                />
              </div>
            </div>
          </div>

          {/* Análise Financeira e Status */}
          <div className="space-y-4">
            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
              Crédito e Status
            </h3>
            <div className="grid gap-4 md:grid-cols-2">
              <div>
                <label className="mb-1 block text-sm font-medium">
                  Limite de Crédito (R$)
                </label>
                <Input
                  type="text"
                  value={creditLimitDisplay}
                  onChange={handleCreditLimitChange}
                  placeholder="R$ 0,00"
                />
                {errors.creditLimit && (
                  <p className="mt-1 text-xs text-rose-500">{errors.creditLimit.message}</p>
                )}
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Status do Cliente</label>
                <select
                  {...register("status")}
                  className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
                >
                  <option value="ACTIVE">Ativo (Aprovado)</option>
                  <option value="INACTIVE">Inativo (Suspenso)</option>
                  <option value="DELINQUENT">Inadimplente (Bloqueado)</option>
                </select>
              </div>
            </div>
          </div>

          {/* Endereço */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                <MapPin className="h-4 w-4" /> Endereço
              </h3>
              <p className="text-xs text-muted-foreground">
                Digite o CEP para preenchimento automático
              </p>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              <div>
                <label className="mb-1 block text-sm font-medium">CEP</label>
                <div className="flex gap-2">
                  <Input
                    {...register("zipCode")}
                    onChange={handleCepChange}
                    placeholder="00000-000"
                  />
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={handleCepSearch}
                    disabled={isSearchingCep}
                    size="icon"
                  >
                    {isSearchingCep ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Search className="h-4 w-4" />
                    )}
                  </Button>
                </div>
              </div>

              <div className="md:col-span-2">
                <label className="mb-1 block text-sm font-medium">Logradouro / Rua</label>
                <Input {...register("street")} placeholder="Av. Paulista, Rua..." />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Número</label>
                <Input {...register("number")} placeholder="123 / S/N" />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Complemento</label>
                <Input {...register("complement")} placeholder="Sala 402, Bloco B" />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Bairro</label>
                <Input {...register("district")} placeholder="Centro" />
              </div>

              <div className="md:col-span-2">
                <label className="mb-1 block text-sm font-medium">Cidade</label>
                <Input {...register("city")} placeholder="São Paulo" />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium">Estado (UF)</label>
                <Input {...register("state")} placeholder="SP" maxLength={2} />
              </div>
            </div>
          </div>

          {/* Observações */}
          <div>
            <label className="mb-1 block text-sm font-medium">Observações Internas</label>
            <textarea
              {...register("notes")}
              rows={3}
              className="w-full rounded-md border border-input bg-background p-3 text-sm shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
              placeholder="Anotações comerciais, preferências de locação, histórico..."
            />
          </div>

          </div>

          {/* Rodapé e Botões (Fixo) */}
          <div className="flex items-center justify-end gap-3 border-t px-6 py-4 bg-background shrink-0">
            <Button type="button" variant="secondary" onClick={onClose}>
              Cancelar
            </Button>
            <Button type="submit" disabled={isSaving}>
              {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {customerToEdit ? "Salvar Alterações" : "Cadastrar Cliente"}
            </Button>
          </div>
        </form>
      </Card>
    </div>,
    document.body
  );
}
