import { Link, router } from '@inertiajs/react';
import { Building2, CalendarRange, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import type { GrowthExternalCompany } from '@/hooks/use-growth-advice';
import { yearRangesFrom } from '@/lib/growth-format';
import type { YearRange } from '@/lib/growth-format';
import { cn } from '@/lib/utils';
import {
    client as clientGrowthScore,
    refresh as refreshGrowthScore,
} from '@/routes/growth-score';
import type { ExternalCompany, YearlyFinancials } from '@/types/growth-score';

function companyKey(company: {
    id: string;
    account_type?: string;
    accountType?: string;
}): string {
    return `${company.account_type ?? company.accountType}:${company.id}`;
}

export function GrowthOverviewHeader({
    subtitle,
    companies = [],
    selectedCompany,
    years,
    yearRange,
    onYearRangeChange,
    className,
}: {
    subtitle?: string;
    companies?: ExternalCompany[];
    selectedCompany?: GrowthExternalCompany;
    years: YearlyFinancials[];
    yearRange: YearRange | null;
    onYearRangeChange: (range: YearRange) => void;
    className?: string;
}) {
    const ranges = yearRangesFrom(years);
    const selectedKey = selectedCompany
        ? `${selectedCompany.accountType}:${selectedCompany.id}`
        : '';

    function handleCompanyChange(value: string): void {
        const [accountType, ...idParts] = value.split(':');
        const id = idParts.join(':');

        if (!accountType || id === '') {
            return;
        }

        router.visit(
            clientGrowthScore(id, {
                query: { account_type: accountType },
            }),
        );
    }

    return (
        <div
            className={cn(
                'flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between',
                className,
            )}
        >
            <div className="space-y-1">
                <h1 className="text-2xl font-bold tracking-tight md:text-3xl">
                    Growth Overview
                </h1>
                <p className="text-sm text-muted-foreground">
                    {subtitle ??
                        'AI-powered insights to accelerate your business growth.'}
                </p>
            </div>

            <div className="flex flex-wrap items-center gap-2">
                {companies.length > 0 && selectedCompany ? (
                    <Select
                        value={selectedKey}
                        onValueChange={handleCompanyChange}
                    >
                        <SelectTrigger
                            size="sm"
                            aria-label="Selected company"
                            className="min-w-52 bg-background"
                        >
                            <Building2 className="size-3.5 text-muted-foreground" />
                            <SelectValue placeholder="Select company" />
                        </SelectTrigger>
                        <SelectContent align="end">
                            {companies.map((company) => (
                                <SelectItem
                                    key={companyKey(company)}
                                    value={companyKey(company)}
                                >
                                    {company.name} ·{' '}
                                    {company.account_type === 'xero'
                                        ? 'Xero'
                                        : 'QuickBooks'}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                ) : selectedCompany ? (
                    <div className="flex h-8 items-center gap-2 rounded-md border bg-background px-3 text-sm">
                        <Building2 className="size-3.5 text-muted-foreground" />
                        <span className="max-w-52 truncate">
                            {selectedCompany.name}
                        </span>
                    </div>
                ) : null}

                {ranges.length > 0 && yearRange && (
                    <Select
                        value={yearRange.label}
                        onValueChange={(label) => {
                            const next = ranges.find(
                                (range) => range.label === label,
                            );

                            if (next) {
                                onYearRangeChange(next);
                            }
                        }}
                    >
                        <SelectTrigger
                            size="sm"
                            aria-label="Year range"
                            className="min-w-44 bg-background"
                        >
                            <CalendarRange className="size-3.5 text-muted-foreground" />
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent align="end">
                            {ranges.map((range) => (
                                <SelectItem
                                    key={range.label}
                                    value={range.label}
                                >
                                    {range.label}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                )}

                {selectedCompany && (
                    <Button asChild variant="outline" size="sm">
                        <Link
                            href={refreshGrowthScore(selectedCompany.id)}
                            method="post"
                            as="button"
                            data={{
                                account_type: selectedCompany.accountType,
                                company_name: selectedCompany.name,
                            }}
                        >
                            <RefreshCw />
                            Refresh data
                        </Link>
                    </Button>
                )}
            </div>
        </div>
    );
}
