"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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, ArrowRight, Check, Loader2, Building2, DollarSign, FileText, Eye, CreditCard, Receipt, MapPin, Clock, Briefcase } 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: "Preview", icon: Eye },
    { id: 5, title: "Billing", icon: Receipt },
    { id: 6, title: "Payment", icon: CreditCard },
]

const JOB_POSTING_PRICE = 32.61
const FEATURED_PRICE = 15.00

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({
        // Job Details
        title: "",
        description: "",
        location: "",
        // Salary
        salaryMin: "",
        salaryMax: "",
        salaryType: "monthly",
        currency: "BRL",
        employmentType: "",
        workingHours: "",
        // Company
        companyId: "",
        // Options
        isFeatured: false,
    })

    const [billingData, setBillingData] = useState({
        type: "company" as "company" | "individual",
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
        companyName: "",
        address: "",
        addressLine2: "",
        city: "",
        state: "",
        zip: "",
        country: "BR",
    })

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

    const selectedCompany = companies.find(c => c.id === formData.companyId)
    const totalPrice = JOB_POSTING_PRICE + (formData.isFeatured ? FEATURED_PRICE : 0)

    const canProceed = () => {
        switch (currentStep) {
            case 1:
                return formData.title.length >= 5 && formData.description.length >= 20
            case 2:
                return true
            case 3:
                return formData.companyId !== ""
            case 4:
                return true // Preview is always valid
            case 5:
                return billingData.firstName && billingData.lastName && billingData.email &&
                    (billingData.type === "individual" || billingData.companyName)
            default:
                return true
        }
    }

    const handlePayment = async () => {
        setIsSubmitting(true)
        try {
            // First create the job as draft
            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", // Will be published after payment
            }

            console.log("[DEBUG] Creating draft job:", payload)
            const job = await jobsApi.create(payload)

            // TODO: Create Stripe checkout session and redirect
            // For now, simulate success
            toast.success("Job created! Payment integration coming soon.")
            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)
        }
    }

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

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

    const getCurrencySymbol = (currency: string) => {
        const symbols: Record<string, string> = { BRL: "R$", USD: "$", EUR: "€", GBP: "£", JPY: "¥" }
        return symbols[currency] || currency
    }

    return (
        <div className="max-w-4xl 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 job</h1>
                    <p className="text-muted-foreground">Create your job listing in a few steps</p>
                </div>
            </div>

            {/* Progress Steps */}
            <div className="flex items-center justify-between overflow-x-auto pb-2">
                {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 flex-shrink-0">
                            <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-4 w-4" />}
                                </div>
                                <span
                                    className={cn(
                                        "mt-2 text-xs font-medium whitespace-nowrap",
                                        isActive ? "text-primary" : "text-muted-foreground"
                                    )}
                                >
                                    {step.title}
                                </span>
                            </div>
                            {index < STEPS.length - 1 && (
                                <div
                                    className={cn(
                                        "h-0.5 w-8 md:w-12 mx-1 transition-colors flex-shrink-0",
                                        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 and employment details"}
                        {currentStep === 3 && "Select the company posting this job"}
                        {currentStep === 4 && "Preview how your job will appear"}
                        {currentStep === 5 && "Enter your billing information"}
                        {currentStep === 6 && "Complete your payment to publish"}
                    </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>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>Working Hours</Label>
                                <Input
                                    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: Preview */}
                    {currentStep === 4 && (
                        <div className="space-y-6">
                            {/* Job Preview Card */}
                            <div className="border rounded-lg p-6 space-y-4">
                                <div>
                                    <h2 className="text-2xl font-bold">{formData.title || "Job Title"}</h2>
                                    <p className="text-muted-foreground">{selectedCompany?.name || "Company Name"}</p>
                                </div>

                                <div className="flex flex-wrap gap-4 text-sm">
                                    {formData.location && (
                                        <div className="flex items-center gap-1 text-muted-foreground">
                                            <MapPin className="h-4 w-4" />
                                            {formData.location}
                                        </div>
                                    )}
                                    {(formData.salaryMin || formData.salaryMax) && (
                                        <div className="flex items-center gap-1 text-muted-foreground">
                                            <DollarSign className="h-4 w-4" />
                                            {getCurrencySymbol(formData.currency)}{formData.salaryMin || "?"} - {formData.salaryMax || "?"} {formData.salaryType}
                                        </div>
                                    )}
                                    {formData.employmentType && (
                                        <Badge variant="secondary" className="capitalize">
                                            {formData.employmentType.replace("-", " ")}
                                        </Badge>
                                    )}
                                    {formData.workingHours && (
                                        <div className="flex items-center gap-1 text-muted-foreground">
                                            <Clock className="h-4 w-4" />
                                            {formData.workingHours}
                                        </div>
                                    )}
                                </div>

                                <Separator />

                                <div>
                                    <p className="text-sm whitespace-pre-wrap">{formData.description || "Job description will appear here..."}</p>
                                </div>

                                {selectedCompany && (
                                    <>
                                        <Separator />
                                        <div className="flex items-center gap-3 p-3 bg-muted rounded-lg">
                                            <Building2 className="h-10 w-10 text-muted-foreground" />
                                            <div>
                                                <p className="font-medium">{selectedCompany.name}</p>
                                                <p className="text-sm text-muted-foreground">View company profile</p>
                                            </div>
                                        </div>
                                    </>
                                )}
                            </div>

                            <div className="text-center space-y-2 p-4 bg-green-50 dark:bg-green-950 rounded-lg border border-green-200 dark:border-green-800">
                                <p className="text-green-700 dark:text-green-400 font-medium">Your job offer is ready to be posted!</p>
                            </div>

                            <div className="flex items-center gap-2 p-4 border rounded-lg">
                                <input
                                    type="checkbox"
                                    id="featured"
                                    checked={formData.isFeatured}
                                    onChange={(e) => updateField("isFeatured", e.target.checked)}
                                    className="h-4 w-4"
                                />
                                <Label htmlFor="featured" className="flex-1 cursor-pointer">
                                    <span className="font-medium">Feature this job</span>
                                    <span className="text-muted-foreground text-sm block">
                                        Your job will be highlighted and appear at the top of search results (+${FEATURED_PRICE.toFixed(2)})
                                    </span>
                                </Label>
                            </div>
                        </div>
                    )}

                    {/* Step 5: Billing */}
                    {currentStep === 5 && (
                        <div className="space-y-6">
                            <div className="space-y-3">
                                <Label>You are *</Label>
                                <RadioGroup
                                    value={billingData.type}
                                    onValueChange={(v) => updateBilling("type", v)}
                                    className="space-y-2"
                                >
                                    <div className="flex items-center space-x-2 p-3 border rounded-lg">
                                        <RadioGroupItem value="company" id="company" />
                                        <Label htmlFor="company" className="flex-1 cursor-pointer">Company</Label>
                                    </div>
                                    <div className="flex items-center space-x-2 p-3 border rounded-lg">
                                        <RadioGroupItem value="individual" id="individual" />
                                        <Label htmlFor="individual" className="flex-1 cursor-pointer">Individual</Label>
                                    </div>
                                </RadioGroup>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label>First name *</Label>
                                    <Input
                                        value={billingData.firstName}
                                        onChange={(e) => updateBilling("firstName", e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Last name *</Label>
                                    <Input
                                        value={billingData.lastName}
                                        onChange={(e) => updateBilling("lastName", e.target.value)}
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label>Email *</Label>
                                    <Input
                                        type="email"
                                        value={billingData.email}
                                        onChange={(e) => updateBilling("email", e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Phone</Label>
                                    <Input
                                        value={billingData.phone}
                                        onChange={(e) => updateBilling("phone", e.target.value)}
                                    />
                                </div>
                            </div>

                            {billingData.type === "company" && (
                                <div className="space-y-2">
                                    <Label>Company name *</Label>
                                    <Input
                                        value={billingData.companyName}
                                        onChange={(e) => updateBilling("companyName", e.target.value)}
                                    />
                                </div>
                            )}

                            <div className="space-y-2">
                                <Label>Address *</Label>
                                <Input
                                    placeholder="Address line 1"
                                    value={billingData.address}
                                    onChange={(e) => updateBilling("address", e.target.value)}
                                />
                                <Input
                                    placeholder="Address line 2 (optional)"
                                    value={billingData.addressLine2}
                                    onChange={(e) => updateBilling("addressLine2", e.target.value)}
                                />
                            </div>

                            <div className="grid grid-cols-3 gap-4">
                                <div className="space-y-2">
                                    <Label>City *</Label>
                                    <Input
                                        value={billingData.city}
                                        onChange={(e) => updateBilling("city", e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>State *</Label>
                                    <Input
                                        value={billingData.state}
                                        onChange={(e) => updateBilling("state", e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Zip *</Label>
                                    <Input
                                        value={billingData.zip}
                                        onChange={(e) => updateBilling("zip", e.target.value)}
                                    />
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label>Country *</Label>
                                <Select value={billingData.country} onValueChange={(v) => updateBilling("country", v)}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="BR">Brazil</SelectItem>
                                        <SelectItem value="US">United States</SelectItem>
                                        <SelectItem value="GB">United Kingdom</SelectItem>
                                        <SelectItem value="DE">Germany</SelectItem>
                                        <SelectItem value="JP">Japan</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                    )}

                    {/* Step 6: Payment */}
                    {currentStep === 6 && (
                        <div className="space-y-6">
                            <div className="flex gap-2">
                                <Badge variant="outline" className="px-3 py-1">
                                    <span className="text-blue-600 font-bold">VISA</span>
                                </Badge>
                                <Badge variant="outline" className="px-3 py-1 bg-red-50">
                                    <span className="text-red-600 font-bold">MC</span>
                                </Badge>
                                <Badge variant="outline" className="px-3 py-1 bg-blue-50">
                                    <span className="text-blue-800 font-bold">AMEX</span>
                                </Badge>
                            </div>

                            <div className="space-y-3 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">Your order</span>
                                    <span>1 job posting</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">Duration</span>
                                    <span>30 days</span>
                                </div>
                                {formData.isFeatured && (
                                    <div className="flex justify-between text-green-600">
                                        <span>Featured upgrade</span>
                                        <span>+${FEATURED_PRICE.toFixed(2)}</span>
                                    </div>
                                )}
                                <Separator />
                                <div className="flex justify-between text-lg font-bold">
                                    <span>Total amount due</span>
                                    <span>${totalPrice.toFixed(2)}</span>
                                </div>
                            </div>

                            <div className="space-y-4 p-4 border rounded-lg">
                                <p className="text-center text-muted-foreground">
                                    You will be redirected to Stripe to complete your payment securely.
                                </p>
                            </div>

                            <div className="space-y-2 text-sm text-muted-foreground">
                                <div className="flex items-start gap-2">
                                    <Check className="h-4 w-4 text-green-600 mt-0.5" />
                                    <span>Once you have paid, your job posting will be online within a few minutes!</span>
                                </div>
                                <div className="flex items-start gap-2">
                                    <Check className="h-4 w-4 text-green-600 mt-0.5" />
                                    <span>You will be able to modify the job description at any time</span>
                                </div>
                                <div className="flex items-start gap-2">
                                    <Check className="h-4 w-4 text-green-600 mt-0.5" />
                                    <span>Your job ad will be visible for 30 days</span>
                                </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 < 6 ? (
                    <Button onClick={nextStep} disabled={!canProceed()}>
                        {currentStep === 4 ? `Pay to post - $${totalPrice.toFixed(2)}` : "Continue"}
                        <ArrowRight className="h-4 w-4 ml-2" />
                    </Button>
                ) : (
                    <Button onClick={handlePayment} disabled={isSubmitting} size="lg" className="gap-2">
                        {isSubmitting ? (
                            <>
                                <Loader2 className="h-4 w-4 animate-spin" />
                                Processing...
                            </>
                        ) : (
                            <>
                                <CreditCard className="h-4 w-4" />
                                Pay ${totalPrice.toFixed(2)}
                            </>
                        )}
                    </Button>
                )}
            </div>
        </div>
    )
}
