"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import {
  Building2,
  Mail,
  Lock,
  Eye,
  EyeOff,
  Phone,
  MapPin,
  Users,
  Globe,
  FileText,
  ArrowLeft,
} from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { motion } from "framer-motion";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const companySchema = z.object({
  companyName: z.string().min(2, "Nome da empresa deve ter pelo menos 2 caracteres"),
  cnpj: z.string().min(14, "CNPJ deve ter 14 dígitos"),
  email: z.string().email("Email inválido"),
  password: z.string().min(6, "Senha deve ter pelo menos 6 caracteres"),
  confirmPassword: z.string(),
  phone: z.string().min(10, "Telefone deve ter pelo menos 10 dígitos"),
  website: z.string().url("Website deve ser uma URL válida").optional().or(z.literal("")),
  address: z.string().min(5, "Endereço deve ter pelo menos 5 caracteres"),
  city: z.string().min(2, "Cidade é obrigatória"),
  state: z.string().min(2, "Estado é obrigatório"),
  zipCode: z.string().min(8, "CEP deve ter 8 dígitos"),
  sector: z.string().min(1, "Setor de atuação é obrigatório"),
  companySize: z.string().min(1, "Tamanho da empresa é obrigatório"),
  description: z.string().min(20, "Descrição deve ter pelo menos 20 caracteres"),
  contactPerson: z.string().min(2, "Nome do responsável é obrigatório"),
  contactRole: z.string().min(2, "Cargo do responsável é obrigatório"),
  acceptTerms: z.boolean().refine(val => val === true, "Você deve aceitar os termos"),
  acceptNewsletter: z.boolean().optional(),
}).refine(data => data.password === data.confirmPassword, {
  message: "Senhas não coincidem",
  path: ["confirmPassword"],
});

type CompanyFormData = z.infer<typeof companySchema>;

export default function CompanyRegisterPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<CompanyFormData>({
    resolver: zodResolver(companySchema),
  });

  const acceptTerms = watch("acceptTerms");
  const acceptNewsletter = watch("acceptNewsletter");

  const onSubmit = async (data: CompanyFormData) => {
    setLoading(true);
    try {
      // Simular cadastro
      await new Promise(resolve => setTimeout(resolve, 2000));
      console.log("Dados da empresa:", data);

      // Redirecionar para login após cadastro
      router.push("/login?message=Cadastro realizado com sucesso! Faça login para continuar.");
    } catch (error) {
      console.error("Erro no cadastro:", error);
    } finally {
      setLoading(false);
    }
  };

  const nextStep = () => {
    if (currentStep < 3) setCurrentStep(currentStep + 1);
  };

  const prevStep = () => {
    if (currentStep > 1) setCurrentStep(currentStep - 1);
  };

  const stepVariants = {
    hidden: { opacity: 0, x: 20 },
    visible: { opacity: 1, x: 0 },
    exit: { opacity: 0, x: -20 }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-background to-muted/20 flex">
      {/* Left Panel - Informações */}
      <div className="hidden lg:flex lg:flex-1 bg-gradient-to-br from-primary to-primary/80 p-8 flex-col justify-center items-center text-primary-foreground">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="max-w-md text-center"
        >
          <div className="flex items-center justify-center gap-3 mb-8">
            <Image src="/logohorse.png" alt="GoHorse Jobs" width={80} height={80} className="rounded-lg" />
          </div>

          <h1 className="text-4xl font-bold mb-4">
            Cadastre sua Empresa
          </h1>

          <p className="text-lg opacity-90 leading-relaxed mb-6">
            Encontre os melhores talentos para sua empresa.
            Publique vagas e conecte-se com candidatos qualificados.
          </p>

          <div className="space-y-4 text-left">
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>Publique vagas gratuitamente</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>Acesso a milhares de candidatos</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>Ferramentas de gestão de candidaturas</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>Dashboard completo de recrutamento</span>
            </div>
          </div>
        </motion.div>
      </div>

      {/* Right Panel - Formulário */}
      <div className="flex-1 p-8 flex flex-col justify-center">
        <div className="w-full max-w-md mx-auto">
          {/* Header */}
          <div className="mb-6">
            <Link
              href="/login"
              className="inline-flex items-center gap-2 text-muted-foreground hover:text-foreground mb-4 transition-colors"
            >
              <ArrowLeft className="w-4 h-4" />
              Voltar ao Login
            </Link>

            <h2 className="text-2xl font-bold text-foreground mb-2">
              Criar Conta - Empresa
            </h2>
            <p className="text-muted-foreground">
              Preencha os dados da sua empresa
            </p>
          </div>

          {/* Progress Indicator */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium">Etapa {currentStep} de 3</span>
              <span className="text-sm text-muted-foreground">
                {currentStep === 1 && "Dados da Empresa"}
                {currentStep === 2 && "Endereço e Contato"}
                {currentStep === 3 && "Informações Adicionais"}
              </span>
            </div>
            <div className="w-full bg-muted rounded-full h-2">
              <div
                className="bg-primary h-2 rounded-full transition-all duration-300"
                style={{ width: `${(currentStep / 3) * 100}%` }}
              />
            </div>
          </div>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {/* Step 1: Dados da Empresa */}
            {currentStep === 1 && (
              <motion.div
                key="step1"
                variants={stepVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                className="space-y-4"
              >
                <div className="space-y-2">
                  <Label htmlFor="companyName">Nome da Empresa</Label>
                  <div className="relative">
                    <Building2 className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="companyName"
                      type="text"
                      placeholder="Nome da sua empresa"
                      className="pl-10"
                      {...register("companyName")}
                    />
                  </div>
                  {errors.companyName && (
                    <span className="text-sm text-destructive">{errors.companyName.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="cnpj">CNPJ</Label>
                  <div className="relative">
                    <FileText className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="cnpj"
                      type="text"
                      placeholder="00.000.000/0000-00"
                      className="pl-10"
                      {...register("cnpj")}
                    />
                  </div>
                  {errors.cnpj && (
                    <span className="text-sm text-destructive">{errors.cnpj.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">Email Corporativo</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="contato@empresa.com"
                      className="pl-10"
                      {...register("email")}
                    />
                  </div>
                  {errors.email && (
                    <span className="text-sm text-destructive">{errors.email.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="password">Senha</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Sua senha"
                      className="pl-10 pr-10"
                      {...register("password")}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                  {errors.password && (
                    <span className="text-sm text-destructive">{errors.password.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword">Confirmar Senha</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="confirmPassword"
                      type={showConfirmPassword ? "text" : "password"}
                      placeholder="Confirme sua senha"
                      className="pl-10 pr-10"
                      {...register("confirmPassword")}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    >
                      {showConfirmPassword ? (
                        <EyeOff className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Eye className="h-4 w-4 text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                  {errors.confirmPassword && (
                    <span className="text-sm text-destructive">{errors.confirmPassword.message}</span>
                  )}
                </div>

                <Button type="button" onClick={nextStep} className="w-full">
                  Próxima Etapa
                </Button>
              </motion.div>
            )}

            {/* Step 2: Endereço e Contato */}
            {currentStep === 2 && (
              <motion.div
                key="step2"
                variants={stepVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                className="space-y-4"
              >
                <div className="space-y-2">
                  <Label htmlFor="phone">Telefone</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="phone"
                      type="tel"
                      placeholder="(11) 99999-9999"
                      className="pl-10"
                      {...register("phone")}
                    />
                  </div>
                  {errors.phone && (
                    <span className="text-sm text-destructive">{errors.phone.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="website">Website (opcional)</Label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="website"
                      type="url"
                      placeholder="https://www.empresa.com"
                      className="pl-10"
                      {...register("website")}
                    />
                  </div>
                  {errors.website && (
                    <span className="text-sm text-destructive">{errors.website.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="address">Endereço</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="address"
                      type="text"
                      placeholder="Rua, número, complemento"
                      className="pl-10"
                      {...register("address")}
                    />
                  </div>
                  {errors.address && (
                    <span className="text-sm text-destructive">{errors.address.message}</span>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="city">Cidade</Label>
                    <Input
                      id="city"
                      type="text"
                      placeholder="Sua cidade"
                      {...register("city")}
                    />
                    {errors.city && (
                      <span className="text-sm text-destructive">{errors.city.message}</span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="state">Estado</Label>
                    <Select onValueChange={(value) => setValue("state", value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Estado" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="AC">Acre</SelectItem>
                        <SelectItem value="AL">Alagoas</SelectItem>
                        <SelectItem value="AP">Amapá</SelectItem>
                        <SelectItem value="AM">Amazonas</SelectItem>
                        <SelectItem value="BA">Bahia</SelectItem>
                        <SelectItem value="CE">Ceará</SelectItem>
                        <SelectItem value="DF">Distrito Federal</SelectItem>
                        <SelectItem value="ES">Espírito Santo</SelectItem>
                        <SelectItem value="GO">Goiás</SelectItem>
                        <SelectItem value="MA">Maranhão</SelectItem>
                        <SelectItem value="MT">Mato Grosso</SelectItem>
                        <SelectItem value="MS">Mato Grosso do Sul</SelectItem>
                        <SelectItem value="MG">Minas Gerais</SelectItem>
                        <SelectItem value="PA">Pará</SelectItem>
                        <SelectItem value="PB">Paraíba</SelectItem>
                        <SelectItem value="PR">Paraná</SelectItem>
                        <SelectItem value="PE">Pernambuco</SelectItem>
                        <SelectItem value="PI">Piauí</SelectItem>
                        <SelectItem value="RJ">Rio de Janeiro</SelectItem>
                        <SelectItem value="RN">Rio Grande do Norte</SelectItem>
                        <SelectItem value="RS">Rio Grande do Sul</SelectItem>
                        <SelectItem value="RO">Rondônia</SelectItem>
                        <SelectItem value="RR">Roraima</SelectItem>
                        <SelectItem value="SC">Santa Catarina</SelectItem>
                        <SelectItem value="SP">São Paulo</SelectItem>
                        <SelectItem value="SE">Sergipe</SelectItem>
                        <SelectItem value="TO">Tocantins</SelectItem>
                      </SelectContent>
                    </Select>
                    {errors.state && (
                      <span className="text-sm text-destructive">{errors.state.message}</span>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="zipCode">CEP</Label>
                  <Input
                    id="zipCode"
                    type="text"
                    placeholder="00000-000"
                    {...register("zipCode")}
                  />
                  {errors.zipCode && (
                    <span className="text-sm text-destructive">{errors.zipCode.message}</span>
                  )}
                </div>

                <div className="flex gap-4">
                  <Button type="button" variant="outline" onClick={prevStep} className="flex-1">
                    Voltar
                  </Button>
                  <Button type="button" onClick={nextStep} className="flex-1">
                    Próxima Etapa
                  </Button>
                </div>
              </motion.div>
            )}

            {/* Step 3: Informações Adicionais */}
            {currentStep === 3 && (
              <motion.div
                key="step3"
                variants={stepVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                className="space-y-4"
              >
                <div className="space-y-2">
                  <Label htmlFor="sector">Setor de Atuação</Label>
                  <Select onValueChange={(value) => setValue("sector", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Selecione o setor" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="tecnologia">Tecnologia</SelectItem>
                      <SelectItem value="financeiro">Financeiro</SelectItem>
                      <SelectItem value="saude">Saúde</SelectItem>
                      <SelectItem value="educacao">Educação</SelectItem>
                      <SelectItem value="varejo">Varejo</SelectItem>
                      <SelectItem value="construcao">Construção</SelectItem>
                      <SelectItem value="industria">Indústria</SelectItem>
                      <SelectItem value="servicos">Serviços</SelectItem>
                      <SelectItem value="agricultura">Agricultura</SelectItem>
                      <SelectItem value="transporte">Transporte</SelectItem>
                      <SelectItem value="energia">Energia</SelectItem>
                      <SelectItem value="consultoria">Consultoria</SelectItem>
                      <SelectItem value="marketing">Marketing</SelectItem>
                      <SelectItem value="outros">Outros</SelectItem>
                    </SelectContent>
                  </Select>
                  {errors.sector && (
                    <span className="text-sm text-destructive">{errors.sector.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="companySize">Tamanho da Empresa</Label>
                  <Select onValueChange={(value) => setValue("companySize", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Número de funcionários" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1-10">1 a 10 funcionários</SelectItem>
                      <SelectItem value="11-50">11 a 50 funcionários</SelectItem>
                      <SelectItem value="51-200">51 a 200 funcionários</SelectItem>
                      <SelectItem value="201-500">201 a 500 funcionários</SelectItem>
                      <SelectItem value="501-1000">501 a 1000 funcionários</SelectItem>
                      <SelectItem value="1000+">Mais de 1000 funcionários</SelectItem>
                    </SelectContent>
                  </Select>
                  {errors.companySize && (
                    <span className="text-sm text-destructive">{errors.companySize.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">Descrição da Empresa</Label>
                  <Textarea
                    id="description"
                    placeholder="Descreva sua empresa, cultura, valores e o que oferece aos funcionários..."
                    className="min-h-[100px]"
                    {...register("description")}
                  />
                  {errors.description && (
                    <span className="text-sm text-destructive">{errors.description.message}</span>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="contactPerson">Nome do Responsável</Label>
                    <Input
                      id="contactPerson"
                      type="text"
                      placeholder="Nome completo"
                      {...register("contactPerson")}
                    />
                    {errors.contactPerson && (
                      <span className="text-sm text-destructive">{errors.contactPerson.message}</span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="contactRole">Cargo</Label>
                    <Input
                      id="contactRole"
                      type="text"
                      placeholder="Ex: RH, Gerente"
                      {...register("contactRole")}
                    />
                    {errors.contactRole && (
                      <span className="text-sm text-destructive">{errors.contactRole.message}</span>
                    )}
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="flex items-start space-x-2">
                    <Checkbox
                      id="acceptTerms"
                      checked={acceptTerms}
                      onCheckedChange={(checked) => setValue("acceptTerms", checked as boolean)}
                    />
                    <div className="grid gap-1.5 leading-none">
                      <label
                        htmlFor="acceptTerms"
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        Aceito os{" "}
                        <Link href="/termos" className="text-primary hover:underline">
                          Termos de Uso
                        </Link>{" "}
                        e{" "}
                        <Link href="/privacidade" className="text-primary hover:underline">
                          Política de Privacidade
                        </Link>
                      </label>
                    </div>
                  </div>
                  {errors.acceptTerms && (
                    <span className="text-sm text-destructive">{errors.acceptTerms.message}</span>
                  )}

                  <div className="flex items-start space-x-2">
                    <Checkbox
                      id="acceptNewsletter"
                      checked={acceptNewsletter}
                      onCheckedChange={(checked) => setValue("acceptNewsletter", checked as boolean)}
                    />
                    <div className="grid gap-1.5 leading-none">
                      <label
                        htmlFor="acceptNewsletter"
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        Quero receber dicas de recrutamento e novidades por email
                      </label>
                    </div>
                  </div>
                </div>

                <div className="flex gap-4">
                  <Button type="button" variant="outline" onClick={prevStep} className="flex-1">
                    Voltar
                  </Button>
                  <Button type="submit" disabled={loading} className="flex-1">
                    {loading ? "Criando conta..." : "Criar Conta"}
                  </Button>
                </div>
              </motion.div>
            )}
          </form>

          <div className="mt-6 text-center">
            <p className="text-sm text-muted-foreground">
              Já tem uma conta?{" "}
              <Link href="/login" className="text-primary hover:underline font-medium">
                Faça login
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}