import { ChevronRight, Sparkles } from 'lucide-react';
import { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinner';
import type { GrowthAdviceState } from '@/hooks/use-growth-advice';
import { cn } from '@/lib/utils';
import type { AdvisorActionItem } from '@/types/growth-score';

function scrollToDetails(): void {
    document
        .getElementById('advisor-details')
        ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

export function AdvisorRecommendations({
    adviceState,
    canGenerate,
}: {
    adviceState: GrowthAdviceState;
    canGenerate: boolean;
}) {
    const [activeCategory, setActiveCategory] = useState<
        'critical' | 'focus' | 'nice'
    >('critical');
    const { advice, loading, error, isStale, generateAdvice } = adviceState;
    const items: AdvisorActionItem[] = advice
        ? activeCategory === 'critical'
            ? advice.critical_must_do
            : activeCategory === 'focus'
              ? advice.areas_needing_focus
              : advice.good_to_have
        : [];

    return (
        <Card className="overflow-hidden shadow-sm">
            <CardHeader className="gap-3">
                <div className="flex items-start justify-between gap-2">
                    <CardTitle className="flex items-center gap-2 text-lg">
                        <Sparkles className="size-5 text-primary" />
                        AI Advisor
                    </CardTitle>
                    {isStale && (
                        <Badge
                            variant="outline"
                            className="text-amber-700 dark:text-amber-300"
                        >
                            Earlier sync
                        </Badge>
                    )}
                </div>
                <Button
                    type="button"
                    size="sm"
                    onClick={() => void generateAdvice()}
                    disabled={loading || !canGenerate}
                    className="w-full"
                >
                    {loading ? <Spinner /> : <Sparkles />}
                    {loading
                        ? 'Generating…'
                        : advice
                          ? 'Regenerate Advice'
                          : 'Generate Advice'}
                </Button>
            </CardHeader>
            <CardContent className="space-y-3">
                {error && (
                    <p className="text-sm text-destructive" role="alert">
                        {error}
                    </p>
                )}

                {!canGenerate && (
                    <p className="text-sm text-muted-foreground">
                        Sync at least one year of financial history before
                        generating advice.
                    </p>
                )}

                <div
                    className="grid grid-cols-3 rounded-lg border bg-muted/40 p-1"
                    role="tablist"
                    aria-label="Advisor recommendation categories"
                >
                    {(
                        [
                            ['critical', 'Must Do'],
                            ['focus', 'Focus Next'],
                            ['nice', 'Nice to Have'],
                        ] as const
                    ).map(([key, label]) => (
                        <button
                            key={key}
                            type="button"
                            role="tab"
                            aria-selected={activeCategory === key}
                            onClick={() => setActiveCategory(key)}
                            className={cn(
                                'rounded-md px-1.5 py-1.5 text-[11px] font-medium transition-colors',
                                activeCategory === key
                                    ? 'bg-primary text-primary-foreground shadow-sm'
                                    : 'text-muted-foreground hover:text-foreground',
                            )}
                        >
                            {label}
                        </button>
                    ))}
                </div>

                {loading && advice === null && (
                    <div className="space-y-2">
                        {['one', 'two', 'three'].map((key) => (
                            <div
                                key={key}
                                className="h-16 animate-pulse rounded-xl border bg-muted/60"
                            />
                        ))}
                    </div>
                )}

                {advice && (
                    <ul className="space-y-2">
                        {items.slice(0, 3).map((item, index) => (
                            <li key={item.title}>
                                <button
                                    type="button"
                                    onClick={scrollToDetails}
                                    className="flex w-full items-start gap-3 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted/40"
                                >
                                    <span
                                        className={cn(
                                            'mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-bold',
                                            activeCategory === 'critical'
                                                ? 'bg-red-500/15 text-red-700 dark:text-red-300'
                                                : activeCategory === 'focus'
                                                  ? 'bg-amber-500/15 text-amber-800 dark:text-amber-300'
                                                  : 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300',
                                        )}
                                    >
                                        {index + 1}
                                    </span>
                                    <span className="min-w-0 flex-1">
                                        <span className="block text-sm font-semibold">
                                            {item.title}
                                        </span>
                                        <span className="mt-0.5 line-clamp-2 block text-xs text-muted-foreground">
                                            {item.description}
                                        </span>
                                    </span>
                                    <ChevronRight className="mt-1 size-4 shrink-0 text-muted-foreground" />
                                </button>
                            </li>
                        ))}
                    </ul>
                )}

                {advice && (
                    <button
                        type="button"
                        onClick={scrollToDetails}
                        className="flex items-center gap-1 text-sm font-medium text-primary hover:underline"
                    >
                        View all recommendations
                        <ChevronRight className="size-4" />
                    </button>
                )}
            </CardContent>
        </Card>
    );
}
