import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import {
    defaultRadarQuarters,
    parseRadarQuarters,
    RADAR_COLOR_OPTIONS,
    type RadarPoint,
    type RadarQuarter,
} from "@/components/page-blocks/GrowthRadarChartBlock";

type BlockContent = Record<string, unknown>;

const formRow = "mb-4";
const labelCls = "block text-sm font-medium text-slate-700 mb-1.5";

function emptyPoint(): RadarPoint {
    return {
        dimension: "",
        shortName: "",
        exposure: 0,
        current: 0,
    };
}

function emptyQuarter(index: number): RadarQuarter {
    return {
        id: `q${index + 1}`,
        label: `Q${index + 1}`,
        color: "moss",
        points: [emptyPoint()],
    };
}

function moveItem<T>(items: T[], index: number, direction: -1 | 1): T[] {
    const target = index + direction;
    if (target < 0 || target >= items.length) return items;
    const next = [...items];
    [next[index], next[target]] = [next[target], next[index]];
    return next;
}

export function GrowthRadarChartForm({
    content,
    onChange,
}: {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
}) {
    const eyebrow = typeof content.eyebrow === "string" ? content.eyebrow : "Growth Radar";
    const eyebrowColor = typeof content.eyebrowColor === "string" ? content.eyebrowColor : "salmon";
    const title = typeof content.title === "string" ? content.title : "Exposure vs. Current Level";
    const subtitle = typeof content.subtitle === "string"
        ? content.subtitle
        : "The blue area shows what the student has been exposed to through courses. The orange area shows where they currently are. The gap represents growth opportunity.";
    const exposureLabel = typeof content.exposureLabel === "string"
        ? content.exposureLabel
        : "Exposure (from courses)";
    const currentLabel = typeof content.currentLabel === "string"
        ? content.currentLabel
        : "Current Level";
    const quarters = Array.isArray(content.quarters) && content.quarters.length > 0
        ? parseRadarQuarters(content)
        : defaultRadarQuarters;

    const set = (patch: Partial<BlockContent>) => onChange({ ...content, ...patch });
    const setQuarters = (next: RadarQuarter[]) => set({ quarters: next });
    const updateQuarter = (index: number, patch: Partial<RadarQuarter>) => {
        setQuarters(quarters.map((item, itemIndex) => (
            itemIndex === index ? { ...item, ...patch } : item
        )));
    };
    const setPoints = (quarterIndex: number, points: RadarPoint[]) => {
        updateQuarter(quarterIndex, { points });
    };

    return (
        <>
            <p className="text-[11px] text-slate-500 mb-4 rounded-lg bg-slate-50 border border-slate-200 px-3 py-2">
                Growth Radar chart matching My Growth Plan. Client-side quarter tabs switch the radar and gap
                summary. Optional section fields hide when empty.
            </p>

            <div className={formRow}>
                <label className={labelCls}>Eyebrow (optional)</label>
                <Input
                    value={eyebrow}
                    onChange={(event) => set({ eyebrow: event.target.value })}
                    placeholder="e.g. Growth Radar"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Eyebrow color</label>
                <select
                    value={eyebrowColor}
                    onChange={(event) => set({ eyebrowColor: event.target.value })}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                >
                    {RADAR_COLOR_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>{option.label}</option>
                    ))}
                </select>
            </div>
            <div className={formRow}>
                <label className={labelCls}>Title (optional)</label>
                <Input
                    value={title}
                    onChange={(event) => set({ title: event.target.value })}
                    placeholder="Leave empty to hide"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Subtitle (optional)</label>
                <textarea
                    value={subtitle}
                    onChange={(event) => set({ subtitle: event.target.value })}
                    rows={3}
                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    placeholder="Leave empty to hide"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Exposure legend label</label>
                <Input
                    value={exposureLabel}
                    onChange={(event) => set({ exposureLabel: event.target.value })}
                    placeholder="Exposure (from courses)"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Current level legend label</label>
                <Input
                    value={currentLabel}
                    onChange={(event) => set({ currentLabel: event.target.value })}
                    placeholder="Current Level"
                />
            </div>

            <div className={formRow}>
                <CardEditGroup
                    label="Quarters"
                    layout="grid-2"
                    onAdd={() => setQuarters([...quarters, emptyQuarter(quarters.length)])}
                    addLabel="Add quarter"
                    isEmpty={quarters.length === 0}
                    emptyMessage="No quarters configured."
                >
                    {quarters.map((quarter, index) => (
                        <CardEditPanel
                            key={`${quarter.id}-${index}`}
                            index={index}
                            total={quarters.length}
                            layout="grid-2"
                            positionLabel={`Quarter ${index + 1}`}
                            label={quarter.label || quarter.id}
                            preview={{
                                title: quarter.label || quarter.id,
                                subtitle: `${quarter.points.length} dimension(s)`,
                            }}
                            onMoveUp={index > 0
                                ? () => setQuarters(moveItem(quarters, index, -1))
                                : undefined}
                            onMoveDown={index < quarters.length - 1
                                ? () => setQuarters(moveItem(quarters, index, 1))
                                : undefined}
                            onInsertAfter={() => setQuarters([
                                ...quarters.slice(0, index + 1),
                                emptyQuarter(index + 1),
                                ...quarters.slice(index + 1),
                            ])}
                            onRemove={quarters.length > 1
                                ? () => setQuarters(quarters.filter((_, itemIndex) => itemIndex !== index))
                                : undefined}
                        >
                            <div>
                                <label className={labelCls}>ID</label>
                                <Input
                                    value={quarter.id}
                                    onChange={(event) => updateQuarter(index, { id: event.target.value })}
                                    placeholder="e.g. q1"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Label</label>
                                <Input
                                    value={quarter.label}
                                    onChange={(event) => updateQuarter(index, { label: event.target.value })}
                                    placeholder="e.g. Q1 · Explorer"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Accent color</label>
                                <select
                                    value={quarter.color}
                                    onChange={(event) => updateQuarter(index, { color: event.target.value })}
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                >
                                    {RADAR_COLOR_OPTIONS.map((option) => (
                                        <option key={option.value} value={option.value}>{option.label}</option>
                                    ))}
                                </select>
                            </div>

                            <CardEditGroup
                                label="Points"
                                layout="vertical"
                                onAdd={() => setPoints(index, [...quarter.points, emptyPoint()])}
                                addLabel="Add point"
                                isEmpty={quarter.points.length === 0}
                                emptyMessage="No radar points yet."
                            >
                                {quarter.points.map((point, pointIndex) => (
                                    <CardEditPanel
                                        key={`point-${index}-${pointIndex}`}
                                        index={pointIndex}
                                        total={quarter.points.length}
                                        layout="vertical"
                                        positionLabel={`Point ${pointIndex + 1}`}
                                        label={point.shortName || point.dimension || `Point ${pointIndex + 1}`}
                                        onMoveUp={pointIndex > 0
                                            ? () => setPoints(index, moveItem(quarter.points, pointIndex, -1))
                                            : undefined}
                                        onMoveDown={pointIndex < quarter.points.length - 1
                                            ? () => setPoints(index, moveItem(quarter.points, pointIndex, 1))
                                            : undefined}
                                        onInsertAfter={() => setPoints(index, [
                                            ...quarter.points.slice(0, pointIndex + 1),
                                            emptyPoint(),
                                            ...quarter.points.slice(pointIndex + 1),
                                        ])}
                                        onRemove={quarter.points.length > 1
                                            ? () => setPoints(
                                                index,
                                                quarter.points.filter((_, i) => i !== pointIndex),
                                            )
                                            : undefined}
                                    >
                                        <div>
                                            <label className={labelCls}>Dimension</label>
                                            <Input
                                                value={point.dimension}
                                                onChange={(event) => {
                                                    const next = quarter.points.map((row, rowIndex) => (
                                                        rowIndex === pointIndex
                                                            ? { ...row, dimension: event.target.value }
                                                            : row
                                                    ));
                                                    setPoints(index, next);
                                                }}
                                                placeholder="e.g. Bold Visionary Leader"
                                            />
                                        </div>
                                        <div>
                                            <label className={labelCls}>Short name</label>
                                            <Input
                                                value={point.shortName}
                                                onChange={(event) => {
                                                    const next = quarter.points.map((row, rowIndex) => (
                                                        rowIndex === pointIndex
                                                            ? { ...row, shortName: event.target.value }
                                                            : row
                                                    ));
                                                    setPoints(index, next);
                                                }}
                                                placeholder="e.g. Visionary"
                                            />
                                        </div>
                                        <div className="grid grid-cols-2 gap-3">
                                            <div>
                                                <label className={labelCls}>Exposure %</label>
                                                <Input
                                                    type="number"
                                                    min={0}
                                                    max={100}
                                                    value={point.exposure}
                                                    onChange={(event) => {
                                                        const next = quarter.points.map((row, rowIndex) => (
                                                            rowIndex === pointIndex
                                                                ? {
                                                                    ...row,
                                                                    exposure: Number(event.target.value) || 0,
                                                                }
                                                                : row
                                                        ));
                                                        setPoints(index, next);
                                                    }}
                                                />
                                            </div>
                                            <div>
                                                <label className={labelCls}>Current %</label>
                                                <Input
                                                    type="number"
                                                    min={0}
                                                    max={100}
                                                    value={point.current}
                                                    onChange={(event) => {
                                                        const next = quarter.points.map((row, rowIndex) => (
                                                            rowIndex === pointIndex
                                                                ? {
                                                                    ...row,
                                                                    current: Number(event.target.value) || 0,
                                                                }
                                                                : row
                                                        ));
                                                        setPoints(index, next);
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    </CardEditPanel>
                                ))}
                            </CardEditGroup>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>
        </>
    );
}
