"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 { ArrowLeft, ArrowRight, Check, Loader2, Building2, DollarSign, FileText, Eye } from "lucide-react"
import { jobsApi, adminCompaniesApi, type CreateJobPayload, type AdminCompany } from "@/lib/api"
import { toast } from "sonner"
import { cn } from "@/lib/utils"

const STEPS = [
    { id: 1, title: "Job Details", icon: FileText },
    { id: 2, title: "Salary & Type", icon: DollarSign },
    { id: 3, title: "Company", icon: Building2 },
    { id: 4, title: "Review", icon: Eye },
]

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

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

    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) => {
        setFormData(prev => ({ ...prev, [field]: value }))
    }

    const canProceed = () => {
        switch (currentStep) {
            case 1:
                return formData.title.length >= 5 && formData.description.length >= 20
            case 2:
                return true // Salary is optional
            case 3:
                return formData.companyId !== ""
            default:
                return true
        }
    }

    const handleSubmit = async () => {
        if (!formData.companyId || !formData.title || !formData.description) {
            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: "published",
            }

            console.log("[DEBUG] Submitting job:", payload)
            await jobsApi.create(payload)
            toast.success("Job posted successfully!")
            router.push("/dashboard/jobs")
        } catch (error) {
            console.error("Failed to create job:", error)
            toast.error("Failed to post job. Please try again.")
        } finally {
            setIsSubmitting(false)
        }
    }

    const nextStep = () => {
        if (currentStep < 4 && canProceed()) {
            setCurrentStep(prev => prev + 1)
        }
    }

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

    return (
        <div className="max-w-3xl mx-auto space-y-8">
            {/* 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 new job</h1>
                    <p className="text-muted-foreground">Fill in the details for your job listing</p>
                </div>
            </div>

            {/* Progress Steps */}
            <div className="flex items-center justify-between">
                {STEPS.map((step, index) => {
                    const Icon = step.icon
                    const isActive = currentStep === step.id
                    const isCompleted = currentStep > step.id

                    return (
                        <div key={step.id} className="flex items-center">
                            <div className="flex flex-col items-center">
                                <div
                                    className={cn(
                                        "w-10 h-10 rounded-full flex items-center justify-center border-2 transition-colors",
                                        isCompleted
                                            ? "bg-primary border-primary text-primary-foreground"
                                            : isActive
                                                ? "border-primary text-primary"
                                                : "border-muted-foreground/30 text-muted-foreground"
                                    )}
                                >
                                    {isCompleted ? <Check className="h-5 w-5" /> : <Icon className="h-5 w-5" />}
                                </div>
                                <span
                                    className={cn(
                                        "mt-2 text-xs font-medium",
                                        isActive ? "text-primary" : "text-muted-foreground"
                                    )}
                                >
                                    {step.title}
                                </span>
                            </div>
                            {index < STEPS.length - 1 && (
                                <div
                                    className={cn(
                                        "h-0.5 w-16 mx-2 transition-colors",
                                        currentStep > step.id ? "bg-primary" : "bg-muted-foreground/30"
                                    )}
                                />
                            )}
                        </div>
                    )
                })}
            </div>

            {/* Step Content */}
            <Card>
                <CardHeader>
                    <CardTitle>{STEPS[currentStep - 1].title}</CardTitle>
                    <CardDescription>
                        {currentStep === 1 && "Enter the basic information about this job"}
                        {currentStep === 2 && "Set the compensation details"}
                        {currentStep === 3 && "Select the company posting this job"}
                        {currentStep === 4 && "Review your job listing before publishing"}
                    </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                    {/* Step 1: Job Details */}
                    {currentStep === 1 && (
                        <>
                            <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={8}
                                    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">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>
                        </>
                    )}

                    {/* Step 2: Salary & Type */}
                    {currentStep === 2 && (
                        <>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="salaryMin">Minimum Salary</Label>
                                    <Input
                                        id="salaryMin"
                                        type="number"
                                        placeholder="e.g. 5000"
                                        value={formData.salaryMin}
                                        onChange={(e) => updateField("salaryMin", e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="salaryMax">Maximum Salary</Label>
                                    <Input
                                        id="salaryMax"
                                        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 placeholder="Currency" />
                                        </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 placeholder="Select period" />
                                        </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 type" />
                                        </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>
                                            <SelectItem value="dispatch">Dispatch</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="workingHours">Working Hours</Label>
                                <Input
                                    id="workingHours"
                                    placeholder="e.g. 9:00 - 18:00, Mon-Fri"
                                    value={formData.workingHours}
                                    onChange={(e) => updateField("workingHours", e.target.value)}
                                />
                            </div>
                        </>
                    )}

                    {/* Step 3: Company */}
                    {currentStep === 3 && (
                        <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>
                    )}

                    {/* Step 4: Review */}
                    {currentStep === 4 && (
                        <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <p className="text-sm text-muted-foreground">Job Title</p>
                                    <p className="font-medium">{formData.title || "-"}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-muted-foreground">Company</p>
                                    <p className="font-medium">
                                        {companies.find(c => c.id === formData.companyId)?.name || "-"}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-sm text-muted-foreground">Location</p>
                                    <p className="font-medium">{formData.location || "-"}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-muted-foreground">Employment Type</p>
                                    <p className="font-medium">{formData.employmentType || "-"}</p>
                                </div>
                                <div>
                                    <p className="text-sm text-muted-foreground">Salary</p>
                                    <p className="font-medium">
                                        {formData.salaryMin || formData.salaryMax
                                            ? `${formData.currency} ${formData.salaryMin || "?"} - ${formData.salaryMax || "?"} ${formData.salaryType ? `(${formData.salaryType})` : ""}`
                                            : "-"}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-sm text-muted-foreground">Working Hours</p>
                                    <p className="font-medium">{formData.workingHours || "-"}</p>
                                </div>
                            </div>
                            <div>
                                <p className="text-sm text-muted-foreground mb-1">Description</p>
                                <div className="p-3 bg-muted rounded-md text-sm whitespace-pre-wrap max-h-40 overflow-y-auto">
                                    {formData.description || "-"}
                                </div>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Navigation Buttons */}
            <div className="flex justify-between">
                <Button variant="outline" onClick={prevStep} disabled={currentStep === 1}>
                    <ArrowLeft className="h-4 w-4 mr-2" />
                    Back
                </Button>

                {currentStep < 4 ? (
                    <Button onClick={nextStep} disabled={!canProceed()}>
                        Next
                        <ArrowRight className="h-4 w-4 ml-2" />
                    </Button>
                ) : (
                    <Button onClick={handleSubmit} disabled={isSubmitting}>
                        {isSubmitting ? (
                            <>
                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                Publishing...
                            </>
                        ) : (
                            <>
                                <Check className="h-4 w-4 mr-2" />
                                Publish Job
                            </>
                        )}
                    </Button>
                )}
            </div>
        </div>
    )
}
