import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import {
    defaultPortraitGoals,
    parsePortraitGoals,
    PORTRAIT_GOAL_COLOR_OPTIONS,
    type PortraitGoal,
} from "@/components/page-blocks/PortraitGoalsGridBlock";

type BlockContent = Record<string, unknown>;

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

function emptyGoal(): PortraitGoal {
    return {
        emoji: "🚀",
        title: "",
        color: "valencia",
        characterGoal: "",
        mindsetGoal: "",
    };
}

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 PortraitGoalsGridForm({
    content,
    onChange,
}: {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
}) {
    const stepLabel = typeof content.stepLabel === "string" ? content.stepLabel : "Step 3";
    const stepLabelColor = typeof content.stepLabelColor === "string" ? content.stepLabelColor : "moss";
    const title = typeof content.title === "string" ? content.title : "Portrait of the Learner Goals";
    const subtitle = typeof content.subtitle === "string"
        ? content.subtitle
        : "Each dimension has a Character Goal (observable behavior) and a Mindset Goal (internal shift).";
    const characterGoalLabel = typeof content.characterGoalLabel === "string"
        ? content.characterGoalLabel
        : "Character Goal";
    const mindsetGoalLabel = typeof content.mindsetGoalLabel === "string"
        ? content.mindsetGoalLabel
        : "Mindset Goal";
    const goals = Array.isArray(content.goals) && content.goals.length > 0
        ? parsePortraitGoals(content)
        : defaultPortraitGoals;

    const set = (patch: Partial<BlockContent>) => onChange({ ...content, ...patch });
    const setGoals = (next: PortraitGoal[]) => set({ goals: next });
    const updateGoal = (index: number, patch: Partial<PortraitGoal>) => {
        setGoals(goals.map((item, itemIndex) => (
            itemIndex === index ? { ...item, ...patch } : item
        )));
    };

    return (
        <>
            <p className="text-[11px] text-slate-500 mb-4 rounded-lg bg-slate-50 border border-slate-200 px-3 py-2">
                Portrait Goals grid matching My Growth Plan Step 3. Optional section fields hide when empty.
                Each card supports Character and Mindset goals.
            </p>

            <div className={formRow}>
                <label className={labelCls}>Step label (optional)</label>
                <Input
                    value={stepLabel}
                    onChange={(event) => set({ stepLabel: event.target.value })}
                    placeholder="e.g. Step 3"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Step label color</label>
                <select
                    value={stepLabelColor}
                    onChange={(event) => set({ stepLabelColor: event.target.value })}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                >
                    {PORTRAIT_GOAL_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={2}
                    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}>Character goal label</label>
                <Input
                    value={characterGoalLabel}
                    onChange={(event) => set({ characterGoalLabel: event.target.value })}
                    placeholder="Character Goal"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Mindset goal label</label>
                <Input
                    value={mindsetGoalLabel}
                    onChange={(event) => set({ mindsetGoalLabel: event.target.value })}
                    placeholder="Mindset Goal"
                />
            </div>

            <div className={formRow}>
                <CardEditGroup
                    label="Goals"
                    layout="grid-3"
                    onAdd={() => setGoals([...goals, emptyGoal()])}
                    addLabel="Add goal"
                    isEmpty={goals.length === 0}
                    emptyMessage="No goals configured."
                >
                    {goals.map((goal, index) => (
                        <CardEditPanel
                            key={`goal-${index}`}
                            index={index}
                            total={goals.length}
                            layout="grid-3"
                            positionLabel={`Goal ${index + 1}`}
                            label={goal.title || `Goal ${index + 1}`}
                            preview={{
                                emoji: goal.emoji,
                                title: goal.title,
                                subtitle: goal.characterGoal,
                            }}
                            onMoveUp={index > 0
                                ? () => setGoals(moveItem(goals, index, -1))
                                : undefined}
                            onMoveDown={index < goals.length - 1
                                ? () => setGoals(moveItem(goals, index, 1))
                                : undefined}
                            onInsertAfter={() => setGoals([
                                ...goals.slice(0, index + 1),
                                emptyGoal(),
                                ...goals.slice(index + 1),
                            ])}
                            onRemove={goals.length > 1
                                ? () => setGoals(goals.filter((_, itemIndex) => itemIndex !== index))
                                : undefined}
                        >
                            <div className="grid sm:grid-cols-[auto_1fr] gap-3">
                                <div>
                                    <label className={labelCls}>Emoji</label>
                                    <EmojiPickerField
                                        compact
                                        value={goal.emoji}
                                        onChange={(value) => updateGoal(index, { emoji: value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Title</label>
                                    <Input
                                        value={goal.title}
                                        onChange={(event) => updateGoal(index, { title: event.target.value })}
                                        placeholder="e.g. Bold Visionary Leader"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>Accent color</label>
                                <select
                                    value={goal.color}
                                    onChange={(event) => updateGoal(index, { color: event.target.value })}
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                >
                                    {PORTRAIT_GOAL_COLOR_OPTIONS.map((option) => (
                                        <option key={option.value} value={option.value}>{option.label}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className={labelCls}>Character goal</label>
                                <textarea
                                    value={goal.characterGoal}
                                    onChange={(event) => updateGoal(index, {
                                        characterGoal: event.target.value,
                                    })}
                                    rows={3}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    placeholder="Observable behavior goal"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Mindset goal</label>
                                <textarea
                                    value={goal.mindsetGoal}
                                    onChange={(event) => updateGoal(index, {
                                        mindsetGoal: event.target.value,
                                    })}
                                    rows={3}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    placeholder="Internal shift goal"
                                />
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>
        </>
    );
}
