import { Check, ChevronDown, ChevronRight, Circle } 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 { cn } from '@/lib/utils';
import type { NinetyDayPlan } from '@/types/growth-score';

const phases = [
    { key: 'days_0_30', label: '0–30 Days', phase: 'Stabilize', tone: 'red' },
    {
        key: 'days_31_60',
        label: '31–60 Days',
        phase: 'Strengthen',
        tone: 'amber',
    },
    { key: 'days_61_90', label: '61–90 Days', phase: 'Scale', tone: 'emerald' },
] as const;

const toneClasses = {
    red: 'border-red-500/30 bg-red-500/5',
    amber: 'border-amber-500/30 bg-amber-500/5',
    emerald: 'border-emerald-500/30 bg-emerald-500/5',
};

const timelineTone = {
    red: 'bg-red-500',
    amber: 'bg-amber-500',
    emerald: 'bg-emerald-500',
};

export type NinetyDayProgress = {
    completed: Set<string>;
    openPhase: string | null;
    toggleAction: (actionKey: string) => void;
    setOpenPhase: (phase: string | null) => void;
};

export function useNinetyDayProgress(): NinetyDayProgress {
    const [openPhase, setOpenPhase] = useState<string | null>('days_0_30');
    const [completed, setCompleted] = useState<Set<string>>(new Set());

    function toggleAction(actionKey: string): void {
        setCompleted((current) => {
            const next = new Set(current);

            if (next.has(actionKey)) {
                next.delete(actionKey);
            } else {
                next.add(actionKey);
            }

            return next;
        });
    }

    return {
        completed,
        openPhase,
        toggleAction,
        setOpenPhase,
    };
}

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

export function CompactNinetyDayPlan({
    plan,
    loading,
}: {
    plan?: NinetyDayPlan | null;
    loading?: boolean;
}) {
    return (
        <Card className="overflow-hidden shadow-sm">
            <CardHeader>
                <CardTitle className="text-lg">90-Day Action Plan</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                {loading && !plan && (
                    <div className="h-20 animate-pulse rounded-xl border bg-muted/60" />
                )}

                <div className="grid grid-cols-3 gap-2">
                    {phases.map((phase, index) => (
                        <div key={phase.key} className="min-w-0 text-center">
                            <div className="flex items-center">
                                <span
                                    className={cn(
                                        'size-3 shrink-0 rounded-full',
                                        timelineTone[phase.tone],
                                    )}
                                />
                                {index < phases.length - 1 && (
                                    <span
                                        className={cn(
                                            'mx-1 h-1 flex-1 rounded-full',
                                            timelineTone[phase.tone],
                                        )}
                                    />
                                )}
                            </div>
                            <p className="mt-2 text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">
                                {phase.label}
                            </p>
                            <p className="text-sm font-semibold">
                                {phase.phase}
                            </p>
                            {plan && (
                                <p className="text-[11px] text-muted-foreground">
                                    {plan[phase.key].length} action
                                    {plan[phase.key].length === 1 ? '' : 's'}
                                </p>
                            )}
                        </div>
                    ))}
                </div>

                {!plan && !loading && (
                    <p className="text-sm text-muted-foreground">
                        Generate advisor recommendations to unlock a 90-day
                        plan.
                    </p>
                )}

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

export function NinetyDayActionPlan({
    plan,
    progress,
}: {
    plan: NinetyDayPlan;
    progress: NinetyDayProgress;
}) {
    const { completed, openPhase, toggleAction, setOpenPhase } = progress;

    return (
        <Card id="ninety-day-action-plan">
            <CardHeader className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <CardTitle className="text-lg">
                        90-Day Action Plan
                    </CardTitle>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Recommended next steps organized into practical phases.
                    </p>
                </div>
                <Badge variant="outline">Track progress locally</Badge>
            </CardHeader>
            <CardContent>
                <div className="grid gap-3 xl:grid-cols-3">
                    {phases.map((phase) => {
                        const actions = plan[phase.key];
                        const isOpen = openPhase === phase.key;
                        const completedCount = actions.filter((action, index) =>
                            completed.has(`${phase.key}-${index}-${action}`),
                        ).length;

                        return (
                            <div
                                key={phase.key}
                                className={cn(
                                    'rounded-xl border p-3',
                                    toneClasses[phase.tone],
                                )}
                            >
                                <Button
                                    type="button"
                                    variant="ghost"
                                    className="h-auto w-full justify-between px-1 py-1 text-left"
                                    aria-expanded={isOpen}
                                    onClick={() =>
                                        setOpenPhase(isOpen ? null : phase.key)
                                    }
                                >
                                    <span>
                                        <span className="block text-sm font-semibold">
                                            {phase.label} · {phase.phase}
                                        </span>
                                        <span className="text-xs text-muted-foreground">
                                            {completedCount}/{actions.length}{' '}
                                            complete
                                        </span>
                                    </span>
                                    <ChevronDown
                                        className={cn(
                                            'size-4 transition-transform',
                                            isOpen && 'rotate-180',
                                        )}
                                    />
                                </Button>
                                {isOpen && (
                                    <ul className="mt-3 space-y-2 border-t pt-3">
                                        {actions.map((action, index) => {
                                            const actionKey = `${phase.key}-${index}-${action}`;
                                            const isComplete =
                                                completed.has(actionKey);

                                            return (
                                                <li key={actionKey}>
                                                    <button
                                                        type="button"
                                                        className="flex w-full items-start gap-2 rounded-lg p-2 text-left text-sm transition-colors hover:bg-background/70"
                                                        aria-pressed={
                                                            isComplete
                                                        }
                                                        onClick={() =>
                                                            toggleAction(
                                                                actionKey,
                                                            )
                                                        }
                                                    >
                                                        {isComplete ? (
                                                            <Check className="mt-0.5 size-4 shrink-0 text-emerald-600" />
                                                        ) : (
                                                            <Circle className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                                                        )}
                                                        <span
                                                            className={cn(
                                                                isComplete &&
                                                                    'text-muted-foreground line-through',
                                                            )}
                                                        >
                                                            {action}
                                                        </span>
                                                    </button>
                                                </li>
                                            );
                                        })}
                                    </ul>
                                )}
                            </div>
                        );
                    })}
                </div>
            </CardContent>
        </Card>
    );
}
