"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { useAuth } from "@/contexts/auth-context"
import { getApiUrl } from "@/lib/api-config"

interface Vertical {
    id: number
    name: string
    slug: string
    description: string | null
}

export function BandOnboarding({ onComplete }: { onComplete?: () => void }) {
    const [verticals, setVerticals] = useState<Vertical[]>([])
    const [selected, setSelected] = useState<number[]>([])
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)
    const { token } = useAuth()
    const router = useRouter()

    useEffect(() => {
        async function fetchVerticals() {
            try {
                const res = await fetch(`${getApiUrl()}/verticals`)
                if (res.ok) {
                    const data = await res.json()
                    setVerticals(data)
                }
            } catch (err) {
                console.error("Failed to fetch verticals:", err)
            } finally {
                setLoading(false)
            }
        }
        fetchVerticals()
    }, [])

    const toggleVertical = (id: number) => {
        setSelected(prev =>
            prev.includes(id)
                ? prev.filter(v => v !== id)
                : [...prev, id]
        )
    }

    const handleSubmit = async () => {
        if (selected.length === 0) return

        setSaving(true)
        try {
            const res = await fetch(`${getApiUrl()}/verticals/preferences/bulk`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${token}`
                },
                body: JSON.stringify({
                    vertical_ids: selected,
                    display_mode: "primary"
                })
            })

            if (res.ok) {
                if (onComplete) {
                    onComplete()
                } else {
                    // Navigate to first selected band
                    const firstVertical = verticals.find(v => v.id === selected[0])
                    if (firstVertical) {
                        router.push(`/${firstVertical.slug}`)
                    } else {
                        router.push("/")
                    }
                }
            }
        } catch (err) {
            console.error("Failed to save preferences:", err)
        } finally {
            setSaving(false)
        }
    }

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="text-muted-foreground">Loading bands...</div>
            </div>
        )
    }

    return (
        <div className="max-w-2xl mx-auto space-y-6">
            <div className="text-center space-y-2">
                <h1 className="text-3xl font-bold">Pick Your Bands</h1>
                <p className="text-muted-foreground">
                    Select the bands you follow. You can change this anytime.
                </p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {verticals.map((vertical) => (
                    <Card
                        key={vertical.id}
                        className={`cursor-pointer transition-all ${selected.includes(vertical.id)
                                ? "ring-2 ring-primary"
                                : "hover:bg-accent"
                            }`}
                        onClick={() => toggleVertical(vertical.id)}
                    >
                        <CardHeader className="pb-2">
                            <div className="flex items-center gap-3">
                                <Checkbox
                                    checked={selected.includes(vertical.id)}
                                    onCheckedChange={() => toggleVertical(vertical.id)}
                                />
                                <CardTitle className="text-lg">{vertical.name}</CardTitle>
                            </div>
                        </CardHeader>
                        {vertical.description && (
                            <CardContent>
                                <CardDescription>{vertical.description}</CardDescription>
                            </CardContent>
                        )}
                    </Card>
                ))}
            </div>

            <div className="flex justify-center pt-4">
                <Button
                    size="lg"
                    onClick={handleSubmit}
                    disabled={selected.length === 0 || saving}
                >
                    {saving ? "Saving..." : `Continue with ${selected.length} band${selected.length !== 1 ? "s" : ""}`}
                </Button>
            </div>
        </div>
    )
}
