"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 { 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,
  Globe,
  FileText,
  ArrowLeft,
} from "lucide-react";
import { motion } from "framer-motion";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "@/lib/i18n";
import { LanguageSwitcher } from "@/components/language-switcher";

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

  const companySchema = z.object({
    companyName: z.string().min(2, t("register.company.form.errors.companyName")),
    cnpj: z.string().min(14, t("register.company.form.errors.cnpj")),
    email: z.string().email(t("register.company.form.errors.email")),
    password: z.string().min(6, t("register.company.form.errors.password")),
    confirmPassword: z.string(),
    phone: z.string().min(10, t("register.company.form.errors.phone")),
    website: z.string().url(t("register.company.form.errors.website")).optional().or(z.literal("")),
    address: z.string().min(5, t("register.company.form.errors.address")),
    city: z.string().min(2, t("register.company.form.errors.city")),
    state: z.string().min(2, t("register.company.form.errors.state")),
    zipCode: z.string().min(8, t("register.company.form.errors.zipCode")),
    sector: z.string().min(1, t("register.company.form.errors.industry")),
    companySize: z.string().min(1, t("register.company.form.errors.size")),
    description: z.string().min(20, t("register.company.form.errors.description")),
    contactPerson: z.string().min(2, t("register.company.form.errors.contactName")),
    contactRole: z.string().min(2, t("register.company.form.errors.contactRole")),
    acceptTerms: z.boolean().refine(val => val === true, t("register.company.form.errors.acceptTerms")),
    acceptNewsletter: z.boolean().optional(),
  }).refine(data => data.password === data.confirmPassword, {
    message: t("register.company.form.errors.passwordMismatch"),
    path: ["confirmPassword"],
  });

  type CompanyFormData = z.infer<typeof companySchema>;

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

  const acceptTerms = watch("acceptTerms");
  const acceptNewsletter = watch("acceptNewsletter");
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const onSubmit = async (data: CompanyFormData) => {
    setLoading(true);
    setErrorMsg(null);
    try {
      const { registerCompany } = await import("@/lib/auth");

      await registerCompany({
        companyName: data.companyName,
        cnpj: data.cnpj,
        email: data.email,
        phone: data.phone,
      });

      router.push("/login?message=Empresa registrada com sucesso! Faça login com seu email e a senha padrão: ChangeMe123!");
    } catch (error: any) {
      console.error("Registration error:", error);
      setErrorMsg(error.message || t("register.company.form.errors.generic"));
    } 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 - Information */}
      <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 relative">
        <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">
            {t("register.company.title")}
          </h1>

          <p className="text-lg opacity-90 leading-relaxed mb-6">
            {t("register.company.subtitle")}
          </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>{t("register.company.bullets.free")}</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>{t("register.company.bullets.candidates")}</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>{t("register.company.bullets.tools")}</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-2 h-2 bg-white rounded-full"></div>
              <span>{t("register.company.bullets.dashboard")}</span>
            </div>
          </div>
        </motion.div>
      </div>

      {/* Right Panel - Form */}
      <div className="flex-1 p-8 flex flex-col justify-center relative">
        <div className="absolute top-4 right-4">
          <LanguageSwitcher />
        </div>

        <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" />
              {t("register.company.form.actions.backLogin")}
            </Link>

            <h2 className="text-2xl font-bold text-foreground mb-2">
              {t("register.company.form.title")}
            </h2>
            <p className="text-muted-foreground">
              {t("register.company.form.subtitle")}
            </p>
          </div>

          {/* Progress Indicator */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium">{t("register.company.form.steps.step", { current: currentStep, total: 3 })}</span>
              <span className="text-sm text-muted-foreground">
                {currentStep === 1 && t("register.company.form.steps.details")}
                {currentStep === 2 && t("register.company.form.steps.address")}
                {currentStep === 3 && t("register.company.form.steps.info")}
              </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: Company details */}
            {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">{t("register.company.form.fields.companyName")}</Label>
                  <div className="relative">
                    <Building2 className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="companyName"
                      type="text"
                      placeholder={t("register.company.form.fields.companyNamePlaceholder")}
                      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">{t("register.company.form.fields.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={t("register.company.form.fields.cnpjPlaceholder")}
                      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">{t("register.company.form.fields.email")}</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="email"
                      type="email"
                      placeholder={t("register.company.form.fields.emailPlaceholder")}
                      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">{t("register.company.form.fields.password")}</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={t("register.company.form.fields.passwordPlaceholder")}
                      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">{t("register.company.form.fields.confirmPassword")}</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={t("register.company.form.fields.confirmPasswordPlaceholder")}
                      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">
                  {t("register.company.form.actions.next")}
                </Button>
              </motion.div>
            )}

            {/* Step 2: Address & contact */}
            {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">{t("register.company.form.fields.phone")}</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="phone"
                      type="tel"
                      placeholder={t("register.company.form.fields.phonePlaceholder")}
                      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">{t("register.company.form.fields.website")}</Label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="website"
                      type="url"
                      placeholder={t("register.company.form.fields.websitePlaceholder")}
                      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">{t("register.company.form.fields.address")}</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="address"
                      type="text"
                      placeholder={t("register.company.form.fields.addressPlaceholder")}
                      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">{t("register.company.form.fields.city")}</Label>
                    <Input
                      id="city"
                      type="text"
                      placeholder={t("register.company.form.fields.cityPlaceholder")}
                      {...register("city")}
                    />
                    {errors.city && (
                      <span className="text-sm text-destructive">{errors.city.message}</span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="state">{t("register.company.form.fields.state")}</Label>
                    <Select onValueChange={(value) => setValue("state", value)}>
                      <SelectTrigger>
                        <SelectValue placeholder={t("register.company.form.fields.statePlaceholder")} />
                      </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">{t("register.company.form.fields.zipCode")}</Label>
                  <Input
                    id="zipCode"
                    type="text"
                    placeholder={t("register.company.form.fields.zipCodePlaceholder")}
                    {...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">
                    {t("register.company.form.actions.back")}
                  </Button>
                  <Button type="button" onClick={nextStep} className="flex-1">
                    {t("register.company.form.actions.next")}
                  </Button>
                </div>
              </motion.div>
            )}

            {/* Step 3: Additional information */}
            {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">{t("register.company.form.fields.industry")}</Label>
                  <Select onValueChange={(value) => setValue("sector", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder={t("register.company.form.fields.industryPlaceholder")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="technology">{t("register.company.industries.technology")}</SelectItem>
                      <SelectItem value="finance">{t("register.company.industries.finance")}</SelectItem>
                      <SelectItem value="healthcare">{t("register.company.industries.healthcare")}</SelectItem>
                      <SelectItem value="education">{t("register.company.industries.education")}</SelectItem>
                      <SelectItem value="retail">{t("register.company.industries.retail")}</SelectItem>
                      <SelectItem value="construction">{t("register.company.industries.construction")}</SelectItem>
                      <SelectItem value="industry">{t("register.company.industries.industry")}</SelectItem>
                      <SelectItem value="services">{t("register.company.industries.services")}</SelectItem>
                      <SelectItem value="agriculture">{t("register.company.industries.agriculture")}</SelectItem>
                      <SelectItem value="transport">{t("register.company.industries.transport")}</SelectItem>
                      <SelectItem value="energy">{t("register.company.industries.energy")}</SelectItem>
                      <SelectItem value="consulting">{t("register.company.industries.consulting")}</SelectItem>
                      <SelectItem value="marketing">{t("register.company.industries.marketing")}</SelectItem>
                      <SelectItem value="other">{t("register.company.industries.other")}</SelectItem>
                    </SelectContent>
                  </Select>
                  {errors.sector && (
                    <span className="text-sm text-destructive">{errors.sector.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="companySize">{t("register.company.form.fields.size")}</Label>
                  <Select onValueChange={(value) => setValue("companySize", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder={t("register.company.form.fields.sizePlaceholder")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1-10">{t("register.company.sizes.1-10")}</SelectItem>
                      <SelectItem value="11-50">{t("register.company.sizes.11-50")}</SelectItem>
                      <SelectItem value="51-200">{t("register.company.sizes.51-200")}</SelectItem>
                      <SelectItem value="201-500">{t("register.company.sizes.201-500")}</SelectItem>
                      <SelectItem value="501-1000">{t("register.company.sizes.501-1000")}</SelectItem>
                      <SelectItem value="1000+">{t("register.company.sizes.1000+")}</SelectItem>
                    </SelectContent>
                  </Select>
                  {errors.companySize && (
                    <span className="text-sm text-destructive">{errors.companySize.message}</span>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">{t("register.company.form.fields.description")}</Label>
                  <Textarea
                    id="description"
                    placeholder={t("register.company.form.fields.descriptionPlaceholder")}
                    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">{t("register.company.form.fields.contactName")}</Label>
                    <Input
                      id="contactPerson"
                      type="text"
                      placeholder={t("register.company.form.fields.contactNamePlaceholder")}
                      {...register("contactPerson")}
                    />
                    {errors.contactPerson && (
                      <span className="text-sm text-destructive">{errors.contactPerson.message}</span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="contactRole">{t("register.company.form.fields.contactRole")}</Label>
                    <Input
                      id="contactRole"
                      type="text"
                      placeholder={t("register.company.form.fields.contactRolePlaceholder")}
                      {...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"
                      >
                        {t("register.company.form.fields.acceptTerms")}{" "}
                        <Link href="/terms" className="text-primary hover:underline">
                          {t("terms.title")}
                        </Link>{" "}
                        {t("register.candidate.acceptTerms.and")}{" "}
                        <Link href="/privacy" className="text-primary hover:underline">
                          {t("privacy.title")}
                        </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"
                      >
                        {t("register.company.form.fields.acceptNewsletter")}
                      </label>
                    </div>
                  </div>
                </div>

                <div className="flex gap-4">
                  <Button type="button" variant="outline" onClick={prevStep} className="flex-1">
                    {t("register.company.form.actions.back")}
                  </Button>
                  <Button type="submit" disabled={loading} className="flex-1">
                    {loading ? t("register.company.form.actions.submitting") : t("register.company.form.actions.submit")}
                  </Button>
                </div>
              </motion.div>
            )}
          </form>

          <div className="mt-6 text-center">
            <p className="text-sm text-muted-foreground">
              {t("register.company.form.actions.haveAccount")}{" "}
              <Link href="/login" className="text-primary hover:underline font-medium">
                {t("register.company.form.actions.signIn")}
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
