import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import { ImageIconField } from "./ImageIconField";
import {
    defaultSteeringCommittees,
    parseSteeringCommitteeCards,
    STEERING_COMMITTEE_COLOR_OPTIONS,
    type SteeringCommitteeCard,
} from "@/components/page-blocks/SteeringCommitteesGridBlock";

type BlockContent = Record<string, unknown>;

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

function emptyCommittee(index: number): SteeringCommitteeCard {
    return {
        badgeLabel: `Committee ${index + 1}`,
        emoji: "🧭",
        iconImage: "",
        color: "deep-sea",
        name: "",
        purpose: "",
    };
}

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 SteeringCommitteesGridForm({
    content,
    onChange,
}: {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
}) {
    const title = typeof content.title === "string" ? content.title : "";
    const subtitle = typeof content.subtitle === "string" ? content.subtitle : "";
    const description = typeof content.description === "string" ? content.description : "";
    const committees = Array.isArray(content.committees) && content.committees.length > 0
        ? parseSteeringCommitteeCards(content)
        : defaultSteeringCommittees;

    const set = (patch: Partial<BlockContent>) => onChange({ ...content, ...patch });
    const setCommittees = (next: SteeringCommitteeCard[]) => set({ committees: next });
    const updateCommittee = (index: number, patch: Partial<SteeringCommitteeCard>) => {
        setCommittees(committees.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">
                Reusable committee card grid matching the Steering Committees page. Optional section heading
                fields hide when empty. Use the repeater below for Committee 1, 2, 3, etc.
            </p>

            <div className={formRow}>
                <label className={labelCls}>Section 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}>Section subtitle (optional)</label>
                <Input
                    value={subtitle}
                    onChange={(event) => set({ subtitle: event.target.value })}
                    placeholder="Leave empty to hide"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Section description (optional)</label>
                <textarea
                    value={description}
                    onChange={(event) => set({ description: 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}>
                <CardEditGroup
                    label="Committees"
                    layout="grid-3"
                    onAdd={() => setCommittees([...committees, emptyCommittee(committees.length)])}
                    addLabel="Add committee"
                    isEmpty={committees.length === 0}
                    emptyMessage="No committees configured."
                >
                    {committees.map((committee, index) => (
                        <CardEditPanel
                            key={`${committee.badgeLabel}-${index}`}
                            index={index}
                            total={committees.length}
                            layout="grid-3"
                            positionLabel={`Committee ${index + 1}`}
                            label={committee.name || committee.badgeLabel}
                            preview={{
                                emoji: committee.emoji,
                                title: committee.name || committee.badgeLabel,
                                subtitle: committee.purpose,
                            }}
                            onMoveUp={index > 0
                                ? () => setCommittees(moveItem(committees, index, -1))
                                : undefined}
                            onMoveDown={index < committees.length - 1
                                ? () => setCommittees(moveItem(committees, index, 1))
                                : undefined}
                            onInsertAfter={() => setCommittees([
                                ...committees.slice(0, index + 1),
                                emptyCommittee(index + 1),
                                ...committees.slice(index + 1),
                            ])}
                            onRemove={committees.length > 1
                                ? () => setCommittees(committees.filter((_, itemIndex) => itemIndex !== index))
                                : undefined}
                        >
                            <div className="grid sm:grid-cols-[auto_1fr] gap-3">
                                <div>
                                    <label className={labelCls}>Icon</label>
                                    <EmojiPickerField
                                        compact
                                        value={committee.emoji}
                                        onChange={(value) => updateCommittee(index, { emoji: value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Badge label</label>
                                    <Input
                                        value={committee.badgeLabel}
                                        onChange={(event) => updateCommittee(index, {
                                            badgeLabel: event.target.value,
                                        })}
                                        placeholder="e.g. Committee 1"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>Custom icon image (optional)</label>
                                <ImageIconField
                                    value={committee.iconImage}
                                    onChange={(value) => updateCommittee(index, { iconImage: value })}
                                    placeholder="Upload or paste image URL"
                                />
                                <p className="text-[10px] text-slate-500 mt-1">
                                    When set, the image replaces the emoji in the colored header bar.
                                </p>
                            </div>
                            <div>
                                <label className={labelCls}>Accent color</label>
                                <select
                                    value={committee.color}
                                    onChange={(event) => updateCommittee(index, { color: event.target.value })}
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                >
                                    {STEERING_COMMITTEE_COLOR_OPTIONS.map((option) => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className={labelCls}>Committee title</label>
                                <Input
                                    value={committee.name}
                                    onChange={(event) => updateCommittee(index, { name: event.target.value })}
                                    placeholder="e.g. Writing & Literature Steering Committee"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Description</label>
                                <textarea
                                    value={committee.purpose}
                                    onChange={(event) => updateCommittee(index, {
                                        purpose: event.target.value,
                                    })}
                                    rows={3}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    placeholder="Committee purpose / description"
                                />
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>
        </>
    );
}
