"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Loader2, Building2, DollarSign, FileText, Briefcase, MapPin, Clock } from "lucide-react"
import { jobsApi, adminCompaniesApi, type CreateJobPayload, type AdminCompany } from "@/lib/api"
import { toast } from "sonner"

export default function NewJobPage() {
    const router = useRouter()
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [companies, setCompanies] = useState<AdminCompany[]>([])
    const [loadingCompanies, setLoadingCompanies] = useState(true)

    const [formData, setFormData] = useState({
        // Job Details
        title: "",
        description: "",
        location: "",
        // Salary
        salaryMin: "",
        salaryMax: "",
        salaryType: "monthly",
        currency: "BRL",
        employmentType: "",
        workingHours: "",
        // Company
        companyId: "",
        // Status
        status: "draft" as "draft" | "published",
    })

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

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

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

    const handleSubmit = async (publishNow: boolean = false) => {
        if (!canSubmit()) {
            toast.error("Please fill in all required fields")
            return
        }

        setIsSubmitting(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: publishNow ? "published" : "draft",
            }

            await jobsApi.create(payload)
            toast.success(publishNow ? "Job published successfully!" : "Job saved as draft!")
            router.push("/dashboard/jobs")
        } catch (error) {
            console.error("Failed to create job:", error)
            toast.error("Failed to create job. Please try again.")
        } finally {
            setIsSubmitting(false)
        }
    }

    return (
        <div className="max-w-4xl mx-auto space-y-6">
            {/* Header */}
            <div className="flex items-center gap-4">
                <Button variant="ghost" size="icon" onClick={() => router.back()}>
                    <ArrowLeft className="h-5 w-5" />
                </Button>
                <div>
                    <h1 className="text-3xl font-bold">Post a job</h1>
                    <p className="text-muted-foreground">Fill in the details below to create your job listing</p>
                </div>
            </div>

            {/* Job Details Section */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <FileText className="h-5 w-5" />
                        Job Details
                    </CardTitle>
                    <CardDescription>Basic information about this position</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="space-y-2">
                        <Label htmlFor="title">Job Title *</Label>
                        <Input
                            id="title"
                            placeholder="e.g. Senior Software Engineer"
                            value={formData.title}
                            onChange={(e) => updateField("title", e.target.value)}
                        />
                        {formData.title.length > 0 && formData.title.length < 5 && (
                            <p className="text-xs text-destructive">Title must be at least 5 characters</p>
                        )}
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="description">Job Description *</Label>
                        <Textarea
                            id="description"
                            placeholder="Describe the role, responsibilities, and requirements..."
                            rows={6}
                            value={formData.description}
                            onChange={(e) => updateField("description", e.target.value)}
                        />
                        {formData.description.length > 0 && formData.description.length < 20 && (
                            <p className="text-xs text-destructive">Description must be at least 20 characters</p>
                        )}
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="location" className="flex items-center gap-1">
                            <MapPin className="h-4 w-4" />
                            Location
                        </Label>
                        <Input
                            id="location"
                            placeholder="e.g. São Paulo, SP or Remote"
                            value={formData.location}
                            onChange={(e) => updateField("location", e.target.value)}
                        />
                    </div>
                </CardContent>
            </Card>

            {/* Salary & Type Section */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <DollarSign className="h-5 w-5" />
                        Salary & Contract
                    </CardTitle>
                    <CardDescription>Compensation and employment details</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                            <Label>Minimum Salary</Label>
                            <Input
                                type="number"
                                placeholder="e.g. 5000"
                                value={formData.salaryMin}
                                onChange={(e) => updateField("salaryMin", e.target.value)}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Maximum Salary</Label>
                            <Input
                                type="number"
                                placeholder="e.g. 10000"
                                value={formData.salaryMax}
                                onChange={(e) => updateField("salaryMax", e.target.value)}
                            />
                        </div>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                        <div className="space-y-2">
                            <Label>Currency</Label>
                            <Select value={formData.currency} onValueChange={(v) => updateField("currency", v)}>
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="BRL">R$ (BRL)</SelectItem>
                                    <SelectItem value="USD">$ (USD)</SelectItem>
                                    <SelectItem value="EUR">€ (EUR)</SelectItem>
                                    <SelectItem value="GBP">£ (GBP)</SelectItem>
                                    <SelectItem value="JPY">¥ (JPY)</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>Salary Period</Label>
                            <Select value={formData.salaryType} onValueChange={(v) => updateField("salaryType", v)}>
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="hourly">Per hour</SelectItem>
                                    <SelectItem value="daily">Per day</SelectItem>
                                    <SelectItem value="weekly">Per week</SelectItem>
                                    <SelectItem value="monthly">Per month</SelectItem>
                                    <SelectItem value="yearly">Per year</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>Contract Type</Label>
                            <Select value={formData.employmentType} onValueChange={(v) => updateField("employmentType", v)}>
                                <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="permanent">Permanent</SelectItem>
                                    <SelectItem value="full-time">Full-time</SelectItem>
                                    <SelectItem value="part-time">Part-time</SelectItem>
                                    <SelectItem value="contract">Contract</SelectItem>
                                    <SelectItem value="temporary">Temporary</SelectItem>
                                    <SelectItem value="training">Training</SelectItem>
                                    <SelectItem value="voluntary">Voluntary</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div className="space-y-2">
                        <Label className="flex items-center gap-1">
                            <Clock className="h-4 w-4" />
                            Working Hours
                        </Label>
                        <Input
                            placeholder="e.g. 9:00 - 18:00, Mon-Fri"
                            value={formData.workingHours}
                            onChange={(e) => updateField("workingHours", e.target.value)}
                        />
                    </div>
                </CardContent>
            </Card>

            {/* Company Section */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Building2 className="h-5 w-5" />
                        Company
                    </CardTitle>
                    <CardDescription>Select the company posting this job</CardDescription>
                </CardHeader>
                <CardContent>
                    <div className="space-y-2">
                        <Label>Company *</Label>
                        {loadingCompanies ? (
                            <div className="flex items-center gap-2 text-muted-foreground">
                                <Loader2 className="h-4 w-4 animate-spin" />
                                Loading companies...
                            </div>
                        ) : (
                            <Select value={formData.companyId} onValueChange={(v) => updateField("companyId", v)}>
                                <SelectTrigger><SelectValue placeholder="Select a company" /></SelectTrigger>
                                <SelectContent>
                                    {companies.length === 0 ? (
                                        <SelectItem value="__none" disabled>No companies available</SelectItem>
                                    ) : (
                                        companies.map((company) => (
                                            <SelectItem key={company.id} value={company.id}>
                                                {company.name}
                                            </SelectItem>
                                        ))
                                    )}
                                </SelectContent>
                            </Select>
                        )}
                    </div>
                </CardContent>
            </Card>

            <Separator />

            {/* Action Buttons */}
            <div className="flex justify-between items-center">
                <Button variant="outline" onClick={() => router.back()}>
                    Cancel
                </Button>
                <div className="flex gap-3">
                    <Button
                        variant="outline"
                        onClick={() => handleSubmit(false)}
                        disabled={isSubmitting || !canSubmit()}
                    >
                        {isSubmitting ? (
                            <>
                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                Saving...
                            </>
                        ) : (
                            "Save as Draft"
                        )}
                    </Button>
                    <Button
                        onClick={() => handleSubmit(true)}
                        disabled={isSubmitting || !canSubmit()}
                    >
                        {isSubmitting ? (
                            <>
                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                Publishing...
                            </>
                        ) : (
                            <>
                                <Briefcase className="h-4 w-4 mr-2" />
                                Publish Job
                            </>
                        )}
                    </Button>
                </div>
            </div>
        </div>
    )
}
