import { useState } from 'react';
import { Reveal } from '@/components/motion';
import { Card, CardBody, CardHeader } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input, Select } from '@/components/ui/input';
import { Field } from '@/components/ui/label';
import { cn } from '@/lib/utils';

export type Theme = {
    layout?: 'single' | 'three' | 'right'; align?: 'left' | 'center' | 'right';
    colours?: Partial<Record<'primary' | 'secondary' | 'background' | 'text' | 'button', string>>;
    heading_font?: string; body_font?: string;
    /** Cover page hero image (see CoverImageCard). */
    cover_image?: string | null; cover_image_url?: string | null; cover_alt?: string | null;
};
export type ThemeOptions = { layouts: Record<string, string>; align: Record<string, string>; fonts?: string[] };

const SERIF = ['Playfair Display', 'Merriweather', 'Lora'];
const COLOUR_LABELS = { primary: 'Primary', secondary: 'Secondary', button: 'Button' } as const;

/** Mini diagrams of Quotient's three layout presets. */
function LayoutPic({ kind }: { kind: string }) {
    const bar = 'h-1.5 rounded-full bg-current';
    return (
        <div className="flex h-12 w-full flex-col justify-center gap-1.5 rounded border border-line bg-stone-50 px-2 text-ink-muted/60" aria-hidden>
            {[0, 1].map((i) => kind === 'three'
                ? <div key={i} className="grid grid-cols-[1fr_0.3fr_0.4fr] gap-1"><span className={bar} /><span className={bar} /><span className={bar} /></div>
                : kind === 'right'
                    ? <div key={i} className="grid grid-cols-[1fr_0.35fr] gap-2"><span className={bar} /><span className={cn(bar, 'bg-accent')} /></div>
                    : <div key={i} className="rounded-sm border border-current/30 px-1 py-1"><span className={cn(bar, 'block w-3/4')} /></div>)}
        </div>
    );
}

/**
 * Proposal look: layout preset, alignment, and optional colour / font overrides on top of the
 * company theme (templates inherit the company theme and may override it).
 */
export function ThemeCard({ theme, onChange, options, companyColours, companyFonts, allowOverrides = true, disabled = false, description }: {
    theme: Theme; onChange: (t: Theme) => void; options: ThemeOptions; companyColours: Record<string, string>;
    companyFonts: { heading_font: string; body_font: string }; allowOverrides?: boolean; disabled?: boolean; description?: string;
}) {
    const [custom, setCustom] = useState(!!(theme.colours && Object.keys(theme.colours).length) || !!theme.heading_font || !!theme.body_font);
    const set = (p: Partial<Theme>) => onChange({ ...theme, ...p });
    const fonts = (options.fonts ?? []).filter((f) => !SERIF.includes(f));

    return (
        <Card>
            <CardHeader title="Look & layout" description={description ?? 'How the proposal lays out prices and text.'} />
            <CardBody className="space-y-4">
                <fieldset disabled={disabled}>
                    <legend className="mb-2 text-sm font-medium">Page layout</legend>
                    <div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="Page layout">
                        {Object.entries(options.layouts).map(([k, label]) => (
                            <button key={k} type="button" role="radio" aria-checked={(theme.layout ?? 'single') === k} onClick={() => set({ layout: k as Theme['layout'] })}
                                data-testid={`layout-${k}`}
                                className={cn('space-y-1.5 rounded-md border p-2 text-left text-xs font-medium transition-colors', (theme.layout ?? 'single') === k ? 'border-accent bg-accent-soft text-link-hover' : 'border-line hover:border-accent')}>
                                <LayoutPic kind={k} />{label}
                            </button>
                        ))}
                    </div>
                </fieldset>
                <Field label="Text alignment" htmlFor="theme-align">
                    <Select id="theme-align" disabled={disabled} value={theme.align ?? 'left'} onChange={(e) => set({ align: e.target.value as Theme['align'] })}>
                        {Object.entries(options.align).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                    </Select>
                </Field>
                {allowOverrides && <>
                    <Checkbox label="Override the company colours and fonts" checked={custom} disabled={disabled}
                        onChange={(e) => { setCustom(e.target.checked); if (!e.target.checked) onChange({ layout: theme.layout, align: theme.align }); }} />
                    <Reveal show={custom}>
                        <div className="grid gap-3 sm:grid-cols-3">
                            {(Object.keys(COLOUR_LABELS) as (keyof typeof COLOUR_LABELS)[]).map((k) => (
                                <Field key={k} label={COLOUR_LABELS[k]} htmlFor={`theme-${k}`}>
                                    <div className="flex items-center gap-2">
                                        <input type="color" aria-label={`${COLOUR_LABELS[k]} colour picker`} disabled={disabled}
                                            value={theme.colours?.[k] ?? companyColours[k] ?? '#000000'}
                                            onChange={(e) => set({ colours: { ...theme.colours, [k]: e.target.value.toUpperCase() } })}
                                            className="h-[38px] w-10 shrink-0 cursor-pointer rounded border border-line bg-surface p-1" />
                                        <Input id={`theme-${k}`} disabled={disabled} value={theme.colours?.[k] ?? ''} placeholder={companyColours[k]}
                                            onChange={(e) => {
                                                const v = e.target.value.trim();
                                                const next = { ...theme.colours };
                                                if (!v) delete next[k]; else if (/^#[0-9A-Fa-f]{6}$/.test(v)) next[k] = v.toUpperCase(); else return;
                                                set({ colours: next });
                                            }} />
                                    </div>
                                </Field>
                            ))}
                            <Field label="Heading font" htmlFor="theme-hf">
                                <Select id="theme-hf" disabled={disabled} value={theme.heading_font ?? ''} onChange={(e) => set({ heading_font: e.target.value || undefined })}>
                                    <option value="">Company ({companyFonts.heading_font})</option>
                                    {fonts.map((f) => <option key={f}>{f}</option>)}
                                </Select>
                            </Field>
                            <Field label="Body font" htmlFor="theme-bf">
                                <Select id="theme-bf" disabled={disabled} value={theme.body_font ?? ''} onChange={(e) => set({ body_font: e.target.value || undefined })}>
                                    <option value="">Company ({companyFonts.body_font})</option>
                                    {fonts.map((f) => <option key={f}>{f}</option>)}
                                </Select>
                            </Field>
                        </div>
                        <p className="mt-2 text-xs text-ink-muted">Copying the template to another company drops these overrides so it takes on that company's colours and fonts.</p>
                    </Reveal>
                </>}
            </CardBody>
        </Card>
    );
}
