import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import {
    defaultFishboneBranches,
    defaultFishboneInterventions,
    FISHBONE_COLOR_OPTIONS,
    parseEffectShortLines,
    parseFishboneBranches,
    parseFishboneInterventions,
    type FishboneBranch,
} from "@/components/page-blocks/RootCauseFishboneBlock";

type BlockContent = Record<string, unknown>;

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

function emptyBranch(): FishboneBranch {
    return {
        category: "",
        emoji: "🧠",
        color: "valencia",
        causes: [""],
    };
}

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 RootCauseFishboneForm({
    content,
    onChange,
}: {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
}) {
    const stepLabel = typeof content.stepLabel === "string" ? content.stepLabel : "Step 2";
    const stepLabelColor = typeof content.stepLabelColor === "string" ? content.stepLabelColor : "valencia";
    const title = typeof content.title === "string" ? content.title : "Root Cause Analysis";
    const subtitle = typeof content.subtitle === "string"
        ? content.subtitle
        : "An Ishikawa (fishbone) diagram maps the root causes behind each growth area across six categories.";
    const effect = typeof content.effect === "string"
        ? content.effect
        : "Student struggles with resilience, self-regulation, and confident self-expression";
    const effectLabel = typeof content.effectLabel === "string" ? content.effectLabel : "EFFECT";
    const effectShortLines = Array.isArray(content.effectShortLines)
        ? parseEffectShortLines(content)
        : ["Growth gaps in", "resilience & voice"];
    const branches = Array.isArray(content.branches) && content.branches.length > 0
        ? parseFishboneBranches(content)
        : defaultFishboneBranches;
    const interventionsTitle = typeof content.interventionsTitle === "string"
        ? content.interventionsTitle
        : "🎯 Targeted Interventions";
    const interventions = Array.isArray(content.interventions) && content.interventions.length > 0
        ? parseFishboneInterventions(content)
        : defaultFishboneInterventions;

    const set = (patch: Partial<BlockContent>) => onChange({ ...content, ...patch });
    const setBranches = (next: FishboneBranch[]) => set({ branches: next });
    const updateBranch = (index: number, patch: Partial<FishboneBranch>) => {
        setBranches(branches.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">
                Root Cause fishbone matching My Growth Plan Step 2. Desktop SVG and mobile cards are driven by
                the branches and effect fields below. Optional headers hide when empty.
            </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 2"
                />
            </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"
                >
                    {FISHBONE_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}>Effect (full text)</label>
                <textarea
                    value={effect}
                    onChange={(event) => set({ effect: event.target.value })}
                    rows={2}
                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    placeholder="Shown on mobile effect card"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Effect label</label>
                <Input
                    value={effectLabel}
                    onChange={(event) => set({ effectLabel: event.target.value })}
                    placeholder="EFFECT"
                />
            </div>
            <div className={formRow}>
                <label className={labelCls}>Effect short lines (desktop fish head, one per line)</label>
                <textarea
                    value={effectShortLines.join("\n")}
                    onChange={(event) => set({
                        effectShortLines: event.target.value
                            .split("\n")
                            .map((line) => line.trimEnd()),
                    })}
                    rows={2}
                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    placeholder={"Growth gaps in\nresilience & voice"}
                />
            </div>

            <div className={formRow}>
                <CardEditGroup
                    label="Branches"
                    layout="grid-3"
                    onAdd={() => setBranches([...branches, emptyBranch()])}
                    addLabel="Add branch"
                    isEmpty={branches.length === 0}
                    emptyMessage="No branches configured."
                >
                    {branches.map((branch, index) => (
                        <CardEditPanel
                            key={`branch-${index}`}
                            index={index}
                            total={branches.length}
                            layout="grid-3"
                            positionLabel={`Branch ${index + 1}`}
                            label={branch.category || `Branch ${index + 1}`}
                            preview={{
                                emoji: branch.emoji,
                                title: branch.category,
                                subtitle: `${branch.causes.length} cause(s)`,
                            }}
                            onMoveUp={index > 0
                                ? () => setBranches(moveItem(branches, index, -1))
                                : undefined}
                            onMoveDown={index < branches.length - 1
                                ? () => setBranches(moveItem(branches, index, 1))
                                : undefined}
                            onInsertAfter={() => setBranches([
                                ...branches.slice(0, index + 1),
                                emptyBranch(),
                                ...branches.slice(index + 1),
                            ])}
                            onRemove={branches.length > 1
                                ? () => setBranches(branches.filter((_, itemIndex) => itemIndex !== index))
                                : undefined}
                        >
                            <div className="grid sm:grid-cols-[auto_1fr] gap-3">
                                <div>
                                    <label className={labelCls}>Emoji</label>
                                    <EmojiPickerField
                                        compact
                                        value={branch.emoji}
                                        onChange={(value) => updateBranch(index, { emoji: value })}
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Category</label>
                                    <Input
                                        value={branch.category}
                                        onChange={(event) => updateBranch(index, {
                                            category: event.target.value,
                                        })}
                                        placeholder="e.g. Mindset"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>Accent color</label>
                                <select
                                    value={branch.color}
                                    onChange={(event) => updateBranch(index, { color: event.target.value })}
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                >
                                    {FISHBONE_COLOR_OPTIONS.map((option) => (
                                        <option key={option.value} value={option.value}>{option.label}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className={labelCls}>Causes (one per line)</label>
                                <textarea
                                    value={branch.causes.join("\n")}
                                    onChange={(event) => updateBranch(index, {
                                        causes: event.target.value
                                            .split("\n")
                                            .map((line) => line.trimEnd()),
                                    })}
                                    rows={4}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                    placeholder="One cause per line"
                                />
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>

            <div className={formRow}>
                <label className={labelCls}>Interventions title (optional)</label>
                <Input
                    value={interventionsTitle}
                    onChange={(event) => set({ interventionsTitle: event.target.value })}
                    placeholder="🎯 Targeted Interventions"
                />
            </div>

            <div className={formRow}>
                <CardEditGroup
                    label="Interventions"
                    layout="vertical"
                    onAdd={() => set({ interventions: [...interventions, ""] })}
                    addLabel="Add intervention"
                    isEmpty={interventions.length === 0}
                    emptyMessage="No interventions configured."
                >
                    {interventions.map((item, index) => (
                        <CardEditPanel
                            key={`intervention-${index}`}
                            index={index}
                            total={interventions.length}
                            layout="vertical"
                            positionLabel={`Intervention ${index + 1}`}
                            label={item || `Intervention ${index + 1}`}
                            onMoveUp={index > 0
                                ? () => set({ interventions: moveItem(interventions, index, -1) })
                                : undefined}
                            onMoveDown={index < interventions.length - 1
                                ? () => set({ interventions: moveItem(interventions, index, 1) })
                                : undefined}
                            onInsertAfter={() => set({
                                interventions: [
                                    ...interventions.slice(0, index + 1),
                                    "",
                                    ...interventions.slice(index + 1),
                                ],
                            })}
                            onRemove={interventions.length > 1
                                ? () => set({
                                    interventions: interventions.filter((_, itemIndex) => itemIndex !== index),
                                })
                                : undefined}
                        >
                            <div>
                                <label className={labelCls}>Text</label>
                                <Input
                                    value={item}
                                    onChange={(event) => {
                                        const next = interventions.map((row, rowIndex) => (
                                            rowIndex === index ? event.target.value : row
                                        ));
                                        set({ interventions: next });
                                    }}
                                    placeholder="Intervention description"
                                />
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </div>
        </>
    );
}
