import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import { ImageIconField } from "./ImageIconField";
import {
    defaultOrionPanelContent,
    defaultPublicPanelContent,
    emptyCompetitionItem,
    MONTH_TIMELINE,
} from "@/components/page-blocks/competition/defaults";
import { parseCompetitionPanelContent } from "@/components/page-blocks/competition/parseContent";
import type { CompetitionItem, CompetitionPanelContent } from "@/components/page-blocks/competition/types";

export type BlockContent = Record<string, unknown>;

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

const accentOptions = [
    { value: "primary", label: "Primary" },
    { value: "deep-sea", label: "Deep Sea" },
    { value: "valencia", label: "Valencia" },
    { value: "moss", label: "Moss" },
    { value: "sunflower", label: "Sunflower" },
    { value: "salmon", label: "Salmon" },
    { value: "mist", label: "Mist" },
];

const colorOptions = [
    { value: "deep-sea", label: "Deep Sea" },
    { value: "valencia", label: "Valencia" },
    { value: "salmon", label: "Salmon" },
    { value: "sunflower", label: "Sunflower" },
    { value: "moss", label: "Moss" },
    { value: "mist", label: "Mist" },
];

type CompetitionPanelFormProps = {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
    variant?: "orion" | "public";
    showHeaderHint?: boolean;
};

function serializePanel(panel: CompetitionPanelContent): BlockContent {
    return {
        emoji: panel.emoji,
        title: panel.title,
        subtitle: panel.subtitle,
        description: panel.description,
        accentColor: panel.accentColor,
        flexibleEmoji: panel.flexibleEmoji,
        flexibleTitle: panel.flexibleTitle,
        competitions: panel.competitions,
    };
}

export function CompetitionPanelForm({
    content,
    onChange,
    variant = "orion",
    showHeaderHint = true,
}: CompetitionPanelFormProps) {
    const fallback = variant === "public" ? defaultPublicPanelContent() : defaultOrionPanelContent();
    const panel = parseCompetitionPanelContent(content, fallback);

    const setPanel = (next: CompetitionPanelContent) => onChange(serializePanel(next));
    const setCompetitions = (competitions: CompetitionItem[]) => setPanel({ ...panel, competitions });
    const updateItem = (index: number, patch: Partial<CompetitionItem>) => {
        setCompetitions(panel.competitions.map((item, i) => (i === index ? { ...item, ...patch } : item)));
    };
    const moveItem = (index: number, direction: -1 | 1) => {
        const target = index + direction;
        if (target < 0 || target >= panel.competitions.length) return;
        const next = [...panel.competitions];
        [next[index], next[target]] = [next[target], next[index]];
        setCompetitions(next);
    };
    const insertAfter = (index: number) => {
        setCompetitions([
            ...panel.competitions.slice(0, index + 1),
            emptyCompetitionItem(),
            ...panel.competitions.slice(index + 1),
        ]);
    };
    const duplicateItem = (index: number) => {
        const copy = {
            ...panel.competitions[index],
            title: `${panel.competitions[index].title || "Competition"} (copy)`,
        };
        setCompetitions([
            ...panel.competitions.slice(0, index + 1),
            copy,
            ...panel.competitions.slice(index + 1),
        ]);
    };

    return (
        <>
            {showHeaderHint ? (
                <p className="text-[11px] text-slate-500 mb-4 rounded-lg bg-slate-50 border border-slate-200 px-3 py-2">
                    Timeline panel content. Cards with a month appear on the timeline. Cards without a month
                    appear under Flexible / Ongoing.
                </p>
            ) : null}

            <div className={formRow}>
                <div className="flex gap-2">
                    <div>
                        <label className={labelCls}>Section emoji</label>
                        <EmojiPickerField
                            compact
                            value={panel.emoji}
                            onChange={(value) => setPanel({ ...panel, emoji: value })}
                        />
                    </div>
                    <div className="flex-1">
                        <label className={labelCls}>Section title</label>
                        <Input
                            value={panel.title}
                            onChange={(e) => setPanel({ ...panel, title: e.target.value })}
                            placeholder="Orion Competitions / Public Competitions"
                        />
                    </div>
                </div>
            </div>

            <div className={formRow}>
                <label className={labelCls}>Section subtitle (optional)</label>
                <Input
                    value={panel.subtitle}
                    onChange={(e) => setPanel({ ...panel, subtitle: e.target.value })}
                    placeholder="Hidden when empty"
                />
            </div>

            <div className={formRow}>
                <label className={labelCls}>Section description (optional)</label>
                <textarea
                    value={panel.description}
                    onChange={(e) => setPanel({ ...panel, description: e.target.value })}
                    rows={2}
                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    placeholder="Hidden when empty"
                />
            </div>

            <div className={formRow}>
                <label className={labelCls}>Accent color</label>
                <select
                    value={panel.accentColor}
                    onChange={(e) => setPanel({ ...panel, accentColor: e.target.value })}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                >
                    {accentOptions.map((option) => (
                        <option key={option.value} value={option.value}>
                            {option.label}
                        </option>
                    ))}
                </select>
            </div>

            <div className={formRow}>
                <div className="flex gap-2">
                    <div>
                        <label className={labelCls}>Flexible section emoji</label>
                        <EmojiPickerField
                            compact
                            value={panel.flexibleEmoji}
                            onChange={(value) => setPanel({ ...panel, flexibleEmoji: value })}
                        />
                    </div>
                    <div className="flex-1">
                        <label className={labelCls}>Flexible section title</label>
                        <Input
                            value={panel.flexibleTitle}
                            onChange={(e) => setPanel({ ...panel, flexibleTitle: e.target.value })}
                            placeholder="Flexible / Ongoing"
                        />
                    </div>
                </div>
            </div>

            <div className={formRow}>
                <CardEditGroup
                    label="Competitions"
                    layout="vertical"
                    onAdd={() => setCompetitions([...panel.competitions, emptyCompetitionItem()])}
                    addLabel="Add competition"
                    hint="Add, insert, reorder, duplicate, or delete competition cards."
                >
                    {panel.competitions.map((card, index) => (
                        <CardEditPanel
                            key={index}
                            index={index}
                            total={panel.competitions.length}
                            layout="vertical"
                            label={card.title || `Competition ${index + 1}`}
                            preview={{
                                emoji: card.icon || "🏆",
                                title: card.title,
                                subtitle: card.category || card.month,
                            }}
                            onMoveUp={index > 0 ? () => moveItem(index, -1) : undefined}
                            onMoveDown={
                                index < panel.competitions.length - 1 ? () => moveItem(index, 1) : undefined
                            }
                            onInsertAfter={() => insertAfter(index)}
                            onRemove={
                                panel.competitions.length > 1
                                    ? () =>
                                          setCompetitions(
                                              panel.competitions.filter((_, itemIndex) => itemIndex !== index),
                                          )
                                    : undefined
                            }
                        >
                            <div>
                                <label className={labelCls}>Competition name</label>
                                <Input
                                    value={card.title}
                                    onChange={(e) => updateItem(index, { title: e.target.value })}
                                />
                            </div>
                            <div className="flex gap-2 flex-wrap">
                                <div>
                                    <label className={labelCls}>Icon emoji</label>
                                    <EmojiPickerField
                                        compact
                                        value={card.icon}
                                        onChange={(value) => updateItem(index, { icon: value })}
                                    />
                                </div>
                                <div className="flex-1 min-w-[180px]">
                                    <label className={labelCls}>Icon image (optional)</label>
                                    <ImageIconField
                                        value={card.iconImage}
                                        onChange={(value) => updateItem(index, { iconImage: value })}
                                        placeholder="Upload, pick an asset, or paste a URL"
                                    />
                                </div>
                            </div>
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>Category / committee</label>
                                    <Input
                                        value={card.category}
                                        onChange={(e) => updateItem(index, { category: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Card color</label>
                                    <select
                                        value={card.color}
                                        onChange={(e) => updateItem(index, { color: e.target.value })}
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    >
                                        {colorOptions.map((option) => (
                                            <option key={option.value} value={option.value}>
                                                {option.label}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                            </div>
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>Timeline month</label>
                                    <select
                                        value={card.month}
                                        onChange={(e) => updateItem(index, { month: e.target.value })}
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    >
                                        <option value="">— Unscheduled —</option>
                                        {MONTH_TIMELINE.map((month) => (
                                            <option key={month} value={month}>
                                                {month}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className={labelCls}>Status badge (optional)</label>
                                    <Input
                                        value={card.badge}
                                        onChange={(e) => updateItem(index, { badge: e.target.value })}
                                        placeholder="e.g. Open / Upcoming"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>Description (optional)</label>
                                <textarea
                                    value={card.description}
                                    onChange={(e) => updateItem(index, { description: e.target.value })}
                                    rows={2}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Public competition (optional)</label>
                                <Input
                                    value={card.publicCompetition}
                                    onChange={(e) => updateItem(index, { publicCompetition: e.target.value })}
                                />
                            </div>
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>Public timing tag</label>
                                    <Input
                                        value={card.publicTiming}
                                        onChange={(e) => updateItem(index, { publicTiming: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Orion month tag</label>
                                    <Input
                                        value={card.orionMonth}
                                        onChange={(e) => updateItem(index, { orionMonth: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>Date / time tag</label>
                                    <Input
                                        value={card.dateTime}
                                        onChange={(e) => updateItem(index, { dateTime: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Method tag</label>
                                    <Input
                                        value={card.method}
                                        onChange={(e) => updateItem(index, { method: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>CTA button text (optional)</label>
                                    <Input
                                        value={card.buttonText}
                                        onChange={(e) => updateItem(index, { buttonText: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>CTA button URL (optional)</label>
                                    <Input
                                        value={card.buttonUrl}
                                        onChange={(e) => updateItem(index, { buttonUrl: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div>
                                <button
                                    type="button"
                                    onClick={() => duplicateItem(index)}
                                    className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
                                >
                                    Duplicate competition
                                </button>
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>
        </>
    );
}
