"use client"

import { useEffect, useState } from "react"
import { Loader2, PlusCircle } from "lucide-react"
import { toast } from "sonner"

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 { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { adminCompaniesApi, jobsApi, type AdminCompany, type CreateJobPayload } from "@/lib/api"

export default function DashboardNewJobPage() {
  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 =
    formData.title.trim().length >= 5 &&
    formData.description.trim().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 cadastrada no dashboard com sucesso")
      setFormData({
        title: "",
        description: "",
        location: "",
        salaryMin: "",
        salaryMax: "",
        salaryType: "monthly",
        currency: "BRL",
        employmentType: "",
        workingHours: "",
        companyId: "",
      })
    } catch (error: any) {
      console.error("Falha ao cadastrar vaga:", error)
      toast.error(error.message || "Falha ao cadastrar vaga")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Nova vaga</h1>
          <p className="text-muted-foreground mt-1">
            Cadastre vagas usando o padrão visual do dashboard.
          </p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <PlusCircle className="h-5 w-5" /> Dados da vaga
          </CardTitle>
          <CardDescription>
            Informe os detalhes obrigatórios para criar a vaga em rascunho.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <Label htmlFor="title">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)}
              />
            </div>

            <div>
              <Label htmlFor="description">Descrição da vaga *</Label>
              <Textarea
                id="description"
                rows={6}
                placeholder="Descreva responsabilidades, requisitos e diferenciais..."
                value={formData.description}
                onChange={(e) => handleInputChange("description", e.target.value)}
              />
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="location">Localização</Label>
                <Input
                  id="location"
                  placeholder="Ex: São Paulo/SP ou Remoto"
                  value={formData.location}
                  onChange={(e) => handleInputChange("location", e.target.value)}
                />
              </div>

              <div>
                <Label>Tipo de contrato</Label>
                <Select
                  value={formData.employmentType}
                  onValueChange={(v) => handleInputChange("employmentType", v)}
                >
                  <SelectTrigger>
                    <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">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)}
                />
              </div>

              <div>
                <Label htmlFor="salaryMax">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)}
                />
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div>
                <Label>Moeda</Label>
                <Select value={formData.currency} onValueChange={(v) => handleInputChange("currency", v)}>
                  <SelectTrigger>
                    <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>Período do salário</Label>
                <Select value={formData.salaryType} onValueChange={(v) => handleInputChange("salaryType", v)}>
                  <SelectTrigger>
                    <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">Jornada de trabalho</Label>
                <Input
                  id="workingHours"
                  placeholder="Ex: 9h às 18h"
                  value={formData.workingHours}
                  onChange={(e) => handleInputChange("workingHours", e.target.value)}
                />
              </div>
            </div>

            <div>
              <Label>Empresa *</Label>
              {loadingCompanies ? (
                <div className="h-10 px-3 flex items-center text-sm text-muted-foreground border 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>
                    <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>

            <Button type="submit" disabled={loading || !canSubmit}>
              {loading ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : null}
              Criar vaga
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
