"use client"

import { useEffect, useState } from "react"
import { Navbar } from "@/components/navbar"
import { Footer } from "@/components/footer"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Check, Briefcase, Loader2, MapPin, DollarSign, Clock, Building2 } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { jobsApi, adminCompaniesApi, type CreateJobPayload, type AdminCompany } from "@/lib/api"
import { toast } from "sonner"

export default function PublicarVagaPage() {
  const [loading, setLoading] = useState(false)
  const [loadingCompanies, setLoadingCompanies] = useState(true)
  const [companies, setCompanies] = useState<AdminCompany[]>([])

  const [formData, setFormData] = useState({
    title: "",
    description: "",
    location: "",
    salaryMin: "",
    salaryMax: "",
    salaryType: "monthly",
    currency: "BRL",
    employmentType: "",
    workingHours: "",
    companyId: "",
  })

  useEffect(() => {
    const loadCompanies = async () => {
      try {
        setLoadingCompanies(true)
        const data = await adminCompaniesApi.list(undefined, 1, 100)
        setCompanies(data.data ?? [])
      } catch (error) {
        console.error("Falha ao carregar empresas:", error)
        toast.error("Falha ao carregar empresas")
      } finally {
        setLoadingCompanies(false)
      }
    }

    loadCompanies()
  }, [])

  const canSubmit = () => {
    return (
      formData.title.length >= 5 &&
      formData.description.length >= 20 &&
      formData.companyId !== ""
    )
  }

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
  }

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

    if (!canSubmit()) {
      toast.error("Preencha os campos obrigatórios")
      return
    }

    setLoading(true)
    try {
      const payload: CreateJobPayload = {
        companyId: formData.companyId,
        title: formData.title,
        description: formData.description,
        location: formData.location || undefined,
        employmentType: formData.employmentType as CreateJobPayload["employmentType"] || undefined,
        salaryMin: formData.salaryMin ? parseFloat(formData.salaryMin) : undefined,
        salaryMax: formData.salaryMax ? parseFloat(formData.salaryMax) : undefined,
        salaryType: formData.salaryType as CreateJobPayload["salaryType"] || undefined,
        currency: formData.currency as CreateJobPayload["currency"] || undefined,
        workingHours: formData.workingHours || undefined,
        status: "draft",
      }

      await jobsApi.create(payload)
      toast.success("Vaga publicada com sucesso! Ela será revisada em breve.")
      setFormData({
        title: "",
        description: "",
        location: "",
        salaryMin: "",
        salaryMax: "",
        salaryType: "monthly",
        currency: "BRL",
        employmentType: "",
        workingHours: "",
        companyId: "",
      })
    } catch (error: any) {
      console.error("Falha ao publicar vaga:", error)
      toast.error(error.message || "Falha ao publicar vaga")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />

      <main className="flex-1 flex">
        <div className="hidden lg:flex lg:w-2/5 bg-[#F0932B] relative overflow-hidden">
          <Image
            src="/6.png"
            alt="Background"
            fill
            className="object-cover"
            quality={100}
            priority
          />
          <div className="absolute inset-0 opacity-10">
            <div className="absolute top-0 left-0 w-full h-full bg-[radial-gradient(circle_at_30%_50%,rgba(255,255,255,0.1)_0%,transparent_50%)]"></div>
          </div>

          <div className="relative z-10 flex flex-col justify-between p-12 text-white">
            <div>
              <h2 className="text-4xl md:text-5xl font-bold mb-6 leading-tight">
                Anuncie vagas de emprego<br />
                de forma rápida e eficiente
              </h2>

              <div className="space-y-4 mb-8">
                <div className="flex items-start gap-3"><Check className="w-5 h-5 mt-1" /><p className="font-semibold">Uma das maiores comunidades de profissionais do mercado</p></div>
                <div className="flex items-start gap-3"><Check className="w-5 h-5 mt-1" /><p className="font-semibold">Plataforma com alta visibilidade e acesso diário</p></div>
                <div className="flex items-start gap-3"><Check className="w-5 h-5 mt-1" /><p className="font-semibold">Grande movimentação de candidaturas todos os dias</p></div>
                <div className="flex items-start gap-3"><Check className="w-5 h-5 mt-1" /><p className="font-semibold">Novos talentos se cadastrando constantemente</p></div>
              </div>
            </div>
          </div>
        </div>

        <div className="flex-1 bg-gray-50 overflow-y-auto">
          <div className="max-w-3xl mx-auto py-12 px-6 md:px-12">
            <div className="text-center mb-8">
              <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-3">
                Anuncie a sua vaga de emprego GRÁTIS!
              </h1>
              <p className="text-gray-600">
                Mais de <span className="font-semibold text-primary">50 mil currículos cadastrados</span>
              </p>
            </div>

            <form onSubmit={handleSubmit} className="space-y-5">
              <div>
                <Label htmlFor="title" className="text-gray-700 mb-1.5 block text-sm">
                  <Briefcase className="inline w-4 h-4 mr-1" /> Título da vaga *
                </Label>
                <Input
                  id="title"
                  placeholder="Ex: Desenvolvedor(a) Full Stack Sênior"
                  value={formData.title}
                  onChange={(e) => handleInputChange("title", e.target.value)}
                  className="h-11 bg-white border-gray-300"
                />
              </div>

              <div>
                <Label htmlFor="description" className="text-gray-700 mb-1.5 block text-sm">Descrição da vaga *</Label>
                <Textarea
                  id="description"
                  placeholder="Descreva responsabilidades, requisitos e diferenciais..."
                  rows={6}
                  value={formData.description}
                  onChange={(e) => handleInputChange("description", e.target.value)}
                  className="bg-white border-gray-300"
                />
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="location" className="text-gray-700 mb-1.5 block text-sm">
                    <MapPin className="inline w-4 h-4 mr-1" /> Localização
                  </Label>
                  <Input
                    id="location"
                    placeholder="Ex: São Paulo/SP ou Remoto"
                    value={formData.location}
                    onChange={(e) => handleInputChange("location", e.target.value)}
                    className="h-11 bg-white border-gray-300"
                  />
                </div>

                <div>
                  <Label className="text-gray-700 mb-1.5 block text-sm">
                    <Clock className="inline w-4 h-4 mr-1" /> Tipo de contrato
                  </Label>
                  <Select value={formData.employmentType} onValueChange={(v) => handleInputChange("employmentType", v)}>
                    <SelectTrigger className="h-11 bg-white border-gray-300">
                      <SelectValue placeholder="Selecione" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="permanent">Permanente</SelectItem>
                      <SelectItem value="full-time">Tempo integral</SelectItem>
                      <SelectItem value="part-time">Meio período</SelectItem>
                      <SelectItem value="contract">Contrato</SelectItem>
                      <SelectItem value="temporary">Temporário</SelectItem>
                      <SelectItem value="training">Estágio/Trainee</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="salaryMin" className="text-gray-700 mb-1.5 block text-sm">
                    <DollarSign className="inline w-4 h-4 mr-1" /> Salário mínimo
                  </Label>
                  <Input
                    id="salaryMin"
                    type="number"
                    min="0"
                    placeholder="Ex: 3000"
                    value={formData.salaryMin}
                    onChange={(e) => handleInputChange("salaryMin", e.target.value)}
                    className="h-11 bg-white border-gray-300"
                  />
                </div>

                <div>
                  <Label htmlFor="salaryMax" className="text-gray-700 mb-1.5 block text-sm">Salário máximo</Label>
                  <Input
                    id="salaryMax"
                    type="number"
                    min="0"
                    placeholder="Ex: 6000"
                    value={formData.salaryMax}
                    onChange={(e) => handleInputChange("salaryMax", e.target.value)}
                    className="h-11 bg-white border-gray-300"
                  />
                </div>
              </div>

              <div className="grid md:grid-cols-3 gap-4">
                <div>
                  <Label className="text-gray-700 mb-1.5 block text-sm">Moeda</Label>
                  <Select value={formData.currency} onValueChange={(v) => handleInputChange("currency", v)}>
                    <SelectTrigger className="h-11 bg-white border-gray-300"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="BRL">BRL - R$</SelectItem>
                      <SelectItem value="USD">USD - $</SelectItem>
                      <SelectItem value="EUR">EUR - €</SelectItem>
                      <SelectItem value="GBP">GBP - £</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label className="text-gray-700 mb-1.5 block text-sm">Período do salário</Label>
                  <Select value={formData.salaryType} onValueChange={(v) => handleInputChange("salaryType", v)}>
                    <SelectTrigger className="h-11 bg-white border-gray-300"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="hourly">Por hora</SelectItem>
                      <SelectItem value="daily">Por dia</SelectItem>
                      <SelectItem value="weekly">Por semana</SelectItem>
                      <SelectItem value="monthly">Por mês</SelectItem>
                      <SelectItem value="yearly">Por ano</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label htmlFor="workingHours" className="text-gray-700 mb-1.5 block text-sm">Jornada de trabalho</Label>
                  <Input
                    id="workingHours"
                    placeholder="Ex: 9h às 18h"
                    value={formData.workingHours}
                    onChange={(e) => handleInputChange("workingHours", e.target.value)}
                    className="h-11 bg-white border-gray-300"
                  />
                </div>
              </div>

              <div>
                <Label className="text-gray-700 mb-1.5 block text-sm">
                  <Building2 className="inline w-4 h-4 mr-1" /> Empresa *
                </Label>
                {loadingCompanies ? (
                  <div className="h-11 px-3 flex items-center text-sm text-gray-500 bg-white border border-gray-300 rounded-md">
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" /> Carregando empresas...
                  </div>
                ) : (
                  <Select value={formData.companyId} onValueChange={(v) => handleInputChange("companyId", v)}>
                    <SelectTrigger className="h-11 bg-white border-gray-300">
                      <SelectValue placeholder="Selecione uma empresa" />
                    </SelectTrigger>
                    <SelectContent>
                      {companies.length === 0 ? (
                        <SelectItem value="__none" disabled>Nenhuma empresa disponível</SelectItem>
                      ) : (
                        companies.map((company) => (
                          <SelectItem key={company.id} value={company.id}>{company.name}</SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                )}
              </div>

              <div className="pt-4">
                <Button
                  type="submit"
                  disabled={loading || !canSubmit()}
                  className="w-full bg-[#F0932B] hover:bg-[#d97d1a] text-white font-bold py-6 rounded-full text-lg transition-colors shadow-lg hover:shadow-xl"
                >
                  {loading ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> PUBLICANDO...</> : "ANUNCIAR VAGA GRÁTIS"}
                </Button>
              </div>

              <div className="text-center pt-4">
                <p className="text-sm text-gray-600">
                  Você é um candidato?{" "}
                  <Link href="/register/user" className="text-primary hover:underline font-medium">
                    Cadastre-se grátis aqui!
                  </Link>
                </p>
              </div>
            </form>

            <div className="text-center mt-8 pt-6 border-t border-gray-200">
              <p className="text-xs text-gray-500">© GoHorse Jobs Brasil. Todos os direitos reservados.</p>
            </div>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}
