import React from 'react';
import Icon from './Icon';

/* ---------- Formatters ---------- */
export const fmtHKD = (n: number | string | null | undefined) =>
    'HK$' + Math.round(Number(n) || 0).toLocaleString('en-HK');

/* ---------- Brand ---------- */
export const OwlMark = ({ height = 30, className = '' }: { height?: number; className?: string }) => (
    <img src="/images/logo-orange.png" alt="Flameowl" className={`owlmark ${className}`}
        style={{ height, width: 'auto', display: 'block' }} />
);

export const Wordmark = () => (
    <span className="brandlock">
        <img src="/images/logo-orange.png" alt="Flameowl" className="owlmark"
            style={{ height: 30, width: 'auto' }} />
        <span className="brandlock__txt">FLAMEOWL</span>
    </span>
);

/* ---------- Avatar ---------- */
export const Avatar = ({ name, size = 30 }: { name: string; size?: number }) => {
    const initials = (name || '?').split(/[\s—(]/).filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase();
    const hues = [18, 152, 198, 262, 38, 330];
    const h = hues[(name || ' ').charCodeAt(0) % hues.length];
    return (
        <span className="avatar" style={{
            width: size, height: size, fontSize: size * 0.38,
            background: `oklch(0.92 0.05 ${h})`, color: `oklch(0.42 0.13 ${h})`,
        }}>{initials}</span>
    );
};

/* ---------- Button ---------- */
type ButtonProps = {
    children: React.ReactNode;
    variant?: 'primary' | 'default' | 'ghost';
    size?: 'sm' | 'md';
    icon?: string;
    onClick?: () => void;
    type?: 'button' | 'submit';
    disabled?: boolean;
};
export const Button = ({ children, variant = 'default', size = 'md', icon, onClick, type = 'button', disabled }: ButtonProps) => (
    <button
        className={`btn btn--${variant} btn--${size}`}
        onClick={onClick}
        type={type}
        disabled={disabled}
    >
        {icon && <Icon name={icon} size={size === 'sm' ? 15 : 16} />}
        {children}
    </button>
);

/* ---------- Badge ---------- */
type BadgeKind = 'good' | 'bad' | 'warn' | 'info' | 'neutral';
export const Badge = ({ kind = 'neutral', children }: { kind?: BadgeKind; children: React.ReactNode }) => (
    <span className={`badge badge--${kind}`}>{children}</span>
);

/* ---------- Sparkline ---------- */
export const Sparkline = ({ data, dir = 'up', w = 78, h = 26 }: { data: number[]; dir?: 'up' | 'down'; w?: number; h?: number }) => {
    const min = Math.min(...data), max = Math.max(...data);
    const rng = max - min || 1;
    const pts = data.map((d, i) => [(i / (data.length - 1)) * w, h - 3 - ((d - min) / rng) * (h - 6)]);
    const path = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
    const col = dir === 'down' ? 'var(--bad)' : 'var(--green)';
    return (
        <svg width={w} height={h} className="spark" style={{ overflow: 'visible' }}>
            <path d={`${path} L${w} ${h} L0 ${h} Z`} fill={col} opacity="0.08" />
            <path d={path} fill="none" stroke={col} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
            <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.4" fill={col} />
        </svg>
    );
};

/* ---------- StatCard ---------- */
type StatCardProps = {
    label: string;
    value: React.ReactNode;
    delta?: string;
    deltaDir?: 'up' | 'down';
    spark?: number[];
    icon?: string;
    accent?: string;
};
export const StatCard = ({ label, value, delta, deltaDir = 'up', spark, icon, accent }: StatCardProps) => (
    <div className="stat">
        <div className="stat__top">
            <span className="stat__label">{label}</span>
            {icon && (
                <span className="stat__icon"
                    style={accent ? { color: accent, background: `color-mix(in oklch, ${accent} 14%, transparent)` } : {}}>
                    <Icon name={icon} size={16} />
                </span>
            )}
        </div>
        <div className="stat__value mono">{value}</div>
        <div className="stat__foot">
            {delta != null && (
                <span className={`delta delta--${deltaDir}`}>
                    <Icon name={deltaDir === 'up' ? 'arrowUp' : 'arrowDown'} size={13} stroke={2.2} />
                    {delta}
                </span>
            )}
            {spark && <Sparkline data={spark} dir={deltaDir} />}
        </div>
    </div>
);

/* ---------- YearPicker ---------- */
type YearPickerProps = {
    year: number | 'all';
    years: number[];
    onChange: (y: number | 'all') => void;
    includeAll?: boolean;
};
export const YearPicker = ({ year, years, onChange, includeAll }: YearPickerProps) => (
    <div className="yearpicker">
        <span className="yearpicker__icon"><Icon name="calendar" size={15} /></span>
        <select value={year as any}
            onChange={e => onChange(e.target.value === 'all' ? 'all' : Number(e.target.value))}>
            {includeAll && <option value="all">All years</option>}
            {years.map(y => <option key={y} value={y}>FY {y}</option>)}
        </select>
        <span className="yearpicker__chev"><Icon name="chevronDown" size={14} /></span>
    </div>
);

/* Helper: filter array by year on a given date field. */
export const filterByYear = <T extends Record<string, any>>(
    items: T[], year: number | 'all', dateField: string,
): T[] => {
    if (year === 'all') return items;
    return items.filter(it => {
        const d = it[dateField];
        if (!d) return false;
        return new Date(d).getFullYear() === year;
    });
};

/* ---------- PeriodPicker (year + optional month) ---------- */
export type Period = { year: number | 'all'; month: number | 'all' };

const MONTH_NAMES = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December',
];

type PeriodPickerProps = {
    period: Period;
    years: number[];
    onChange: (p: Period) => void;
    includeAll?: boolean;
};

export const PeriodPicker = ({ period, years, onChange, includeAll }: PeriodPickerProps) => {
    const setYear = (y: number | 'all') =>
        onChange({ year: y, month: y === 'all' ? 'all' : period.month });
    const setMonth = (m: number | 'all') => onChange({ year: period.year, month: m });
    const monthDisabled = period.year === 'all';

    return (
        <div className="periodpicker">
            <div className="yearpicker">
                <span className="yearpicker__icon"><Icon name="calendar" size={15} /></span>
                <select
                    value={period.year as any}
                    onChange={e => setYear(e.target.value === 'all' ? 'all' : Number(e.target.value))}>
                    {includeAll && <option value="all">All years</option>}
                    {years.map(y => <option key={y} value={y}>FY {y}</option>)}
                </select>
                <span className="yearpicker__chev"><Icon name="chevronDown" size={14} /></span>
            </div>
            <div className={`yearpicker ${monthDisabled ? 'is-disabled' : ''}`}>
                <select
                    value={period.month as any}
                    disabled={monthDisabled}
                    onChange={e => setMonth(e.target.value === 'all' ? 'all' : Number(e.target.value))}>
                    <option value="all">All months</option>
                    {MONTH_NAMES.map((name, i) => (
                        <option key={i + 1} value={i + 1}>{name}</option>
                    ))}
                </select>
                <span className="yearpicker__chev"><Icon name="chevronDown" size={14} /></span>
            </div>
        </div>
    );
};

/* Helper: filter by year+optional-month on a given date field. */
export const filterByPeriod = <T extends Record<string, any>>(
    items: T[], period: Period, dateField: string,
): T[] => {
    if (period.year === 'all' && period.month === 'all') return items;
    return items.filter(it => {
        const d = it[dateField];
        if (!d) return false;
        const date = new Date(d);
        const y = date.getFullYear();
        const m = date.getMonth() + 1;
        if (period.year !== 'all' && y !== period.year) return false;
        if (period.month !== 'all' && m !== period.month) return false;
        return true;
    });
};

/* Helper: derive available years from items' date field, descending, including current. */
export const deriveYears = (items: any[], dateField: string): number[] => {
    const current = new Date().getFullYear();
    const set = new Set<number>([current]);
    items.forEach(it => {
        const d = it[dateField];
        if (d) {
            const y = new Date(d).getFullYear();
            if (!isNaN(y)) set.add(y);
        }
    });
    return Array.from(set).sort((a, b) => b - a);
};

/* ---------- SearchInput ---------- */
type SearchInputProps = {
    value: string;
    onChange: (v: string) => void;
    placeholder?: string;
    width?: number;
};
export const SearchInput = ({ value, onChange, placeholder = 'Search…', width = 240 }: SearchInputProps) => (
    <div className="searchinput" style={{ width }}>
        <Icon name="search" size={15} className="searchinput__icon" />
        <input
            value={value}
            onChange={e => onChange(e.target.value)}
            placeholder={placeholder}
        />
        {value && (
            <button className="searchinput__clear" onClick={() => onChange('')} aria-label="Clear">
                <Icon name="x" size={13} />
            </button>
        )}
    </div>
);

/* ---------- PageToolbar ---------- */
type PageToolbarProps = {
    title: string;
    subtitle?: string;
    filters?: React.ReactNode;
    actions?: React.ReactNode;
};
export const PageToolbar = ({ title, subtitle, filters, actions }: PageToolbarProps) => (
    <div className="pagehead">
        <div className="pagehead__row">
            <div>
                <h1 className="pagehead__title">{title}</h1>
                {subtitle && <p className="pagehead__sub">{subtitle}</p>}
            </div>
            <div className="pagehead__actions">
                {filters}
                {actions}
            </div>
        </div>
    </div>
);

/* ---------- PageHeader ---------- */
type PageHeaderProps = {
    title: string;
    subtitle?: string;
    actions?: React.ReactNode;
    kpis?: { label: string; value: React.ReactNode; color?: string }[];
};
export const PageHeader = ({ title, subtitle, actions, kpis }: PageHeaderProps) => (
    <div className="pagehead">
        <div className="pagehead__row">
            <div>
                <h1 className="pagehead__title">{title}</h1>
                {subtitle && <p className="pagehead__sub">{subtitle}</p>}
            </div>
            {actions && <div className="pagehead__actions">{actions}</div>}
        </div>
        {kpis && (
            <div className="minikpis">
                {kpis.map((k, i) => (
                    <div key={i} className="minikpi">
                        <span className="minikpi__label">{k.label}</span>
                        <span className="minikpi__value mono" style={k.color ? { color: k.color } : {}}>{k.value}</span>
                    </div>
                ))}
            </div>
        )}
    </div>
);
