import { Button } from '@/components/ui/button';
import { GripVertical, Plus, Trash2 } from '@/lib/icons';
import { useMemo } from 'react';
interface FieldProps {
    label: string;
    value: string;
    onChange: (value: string) => void;
    multiline?: boolean;
    placeholder?: string;
}
function Field({ label, value, onChange, multiline, placeholder }: FieldProps) {
    return (
        <label className="grid gap-1.5">
            {' '}
            <span className="text-sm font-medium">{label}</span>{' '}
            {multiline ? (
                <textarea
                    rows={3}
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    placeholder={placeholder}
                    className="bg-background focus-visible:outline-ring w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-2"
                />
            ) : (
                <input
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    placeholder={placeholder}
                    className="bg-background focus-visible:outline-ring w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-2"
                />
            )}{' '}
        </label>
    );
}
const BLOCK_TYPES = [
    ['rich_text', 'Rich Text'],
    ['feature_grid', 'Feature Grid'],
    ['stat_band', 'Statistics Band'],
    ['cta', 'Call to Action'],
    ['card_grid', 'Card Grid'],
    ['education_levels', 'Education Levels'],
    ['facility_highlights', 'Facility Highlights'],
    ['inquiry_form', 'Inquiry Form'],
    ['testimonial_carousel', 'Testimonial Carousel'],
    ['news_feed', 'News Feed'],
] as const;
function defaultContent(type: string): Record<string, any> {
    switch (type) {
        case 'rich_text':
            return { eyebrow: '', title: '', subtitle: '', body: '' };
        case 'feature_grid':
        case 'card_grid':
            return { eyebrow: '', title: '', subtitle: '', items: [{ title: '', body: '' }] };
        case 'stat_band':
            return { items: [{ value: '', label: '' }] };
        case 'cta':
            return { eyebrow: '', title: '', body: '', href: '', label: '' };
        case 'education_levels':
            return { eyebrow: '', title: '', subtitle: '', levels: [{ title: '', description: '', grades: [] }] };
        case 'facility_highlights':
            return { eyebrow: '', title: '', items: [{ icon: 'CheckCircle2', text: '' }] };
        case 'inquiry_form':
            return { eyebrow: '', title: '', body: '', cta_label: '', grades: [] };
        case 'testimonial_carousel':
            return { eyebrow: '', title: '', subtitle: '' };
        case 'news_feed':
            return { eyebrow: '', title: '' };
        default:
            return {};
    }
}
interface BlockContentEditorProps {
    type: string;
    content: Record<string, any>;
    onTypeChange: (type: string) => void;
    onContentChange: (content: Record<string, any>) => void;
}
export function BlockContentEditor({ type, content, onTypeChange, onContentChange }: BlockContentEditorProps) {
    const safeContent = useMemo(() => content ?? {}, [content]);
    function setField(field: string, value: any) {
        onContentChange({ ...safeContent, [field]: value });
    }
    return (
        <div className="grid gap-4">
            {' '}
            <div className="grid gap-4 md:grid-cols-2">
                {' '}
                <label className="grid gap-1.5">
                    {' '}
                    <span className="text-sm font-medium">Block Type</span>{' '}
                    <select
                        value={type}
                        onChange={(e) => {
                            onTypeChange(e.target.value);
                            onContentChange(defaultContent(e.target.value));
                        }}
                        className="bg-background focus-visible:outline-ring w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-2"
                    >
                        {' '}
                        {BLOCK_TYPES.map(([value, label]) => (
                            <option key={value} value={value}>
                                {label}
                            </option>
                        ))}{' '}
                    </select>{' '}
                </label>{' '}
            </div>{' '}
            <BasicFields type={type} content={safeContent} setField={setField} />{' '}
            <ArrayFields type={type} content={safeContent} setField={setField} />{' '}
        </div>
    );
}
function BasicFields({ type, content, setField }: { type: string; content: Record<string, any>; setField: (field: string, value: any) => void }) {
    const fields = useMemo(() => {
        const common: string[] = [];
        if ('eyebrow' in content) common.push('eyebrow');
        if ('title' in content) common.push('title');
        if ('subtitle' in content) common.push('subtitle');
        if ('body' in content || type === 'rich_text') common.push('body');
        if ('cta_label' in content) common.push('cta_label');
        if ('href' in content) common.push('href');
        if ('label' in content) common.push('label');
        return common;
    }, [type, content]);
    const multilineFields = ['subtitle', 'body'];
    return (
        <>
            {' '}
            {fields.map((field) => (
                <Field
                    key={field}
                    label={field.replaceAll('_', ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
                    value={String(content[field] ?? '')}
                    onChange={(value) => setField(field, value)}
                    multiline={multilineFields.includes(field)}
                    placeholder={`Enter ${field.replaceAll('_', ' ')}...`}
                />
            ))}{' '}
        </>
    );
}
function ArrayFields({ type, content, setField }: { type: string; content: Record<string, any>; setField: (field: string, value: any) => void }) {
    if (type === 'education_levels') {
        const levels = Array.isArray(content.levels) ? content.levels : [];
        return (
            <div className="grid gap-3">
                {' '}
                <div className="flex items-center justify-between">
                    {' '}
                    <span className="text-sm font-medium">Education Levels</span>{' '}
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => setField('levels', [...levels, { title: '', description: '', grades: [] }])}
                    >
                        {' '}
                        <Plus className="size-3" /> Add Level{' '}
                    </Button>{' '}
                </div>{' '}
                {levels.map((level: Record<string, any>, index: number) => (
                    <div key={index} className="bg-muted/30 rounded-md border p-3">
                        {' '}
                        <div className="flex items-start justify-between gap-2">
                            {' '}
                            <div className="flex items-center gap-2">
                                {' '}
                                <GripVertical className="text-muted-foreground/40 size-4" />{' '}
                                <span className="text-muted-foreground text-xs font-semibold uppercase">Level {index + 1}</span>{' '}
                            </div>{' '}
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() =>
                                    setField(
                                        'levels',
                                        levels.filter((_: any, i: number) => i !== index),
                                    )
                                }
                            >
                                {' '}
                                <Trash2 className="text-destructive size-3" />{' '}
                            </Button>{' '}
                        </div>{' '}
                        <div className="mt-3 grid gap-3">
                            {' '}
                            <Field
                                label="Title"
                                value={level.title ?? ''}
                                onChange={(value) => {
                                    const updated = [...levels];
                                    updated[index] = { ...updated[index], title: value };
                                    setField('levels', updated);
                                }}
                            />{' '}
                            <Field
                                label="Description"
                                value={level.description ?? ''}
                                onChange={(value) => {
                                    const updated = [...levels];
                                    updated[index] = { ...updated[index], description: value };
                                    setField('levels', updated);
                                }}
                                multiline
                            />{' '}
                            <Field
                                label="Grades (comma separated)"
                                value={Array.isArray(level.grades) ? level.grades.join(', ') : ''}
                                onChange={(value) => {
                                    const updated = [...levels];
                                    updated[index] = {
                                        ...updated[index],
                                        grades: value
                                            .split(',')
                                            .map((g: string) => g.trim())
                                            .filter(Boolean),
                                    };
                                    setField('levels', updated);
                                }}
                            />{' '}
                        </div>{' '}
                    </div>
                ))}{' '}
            </div>
        );
    }
    if (type === 'feature_grid' || type === 'card_grid' || type === 'facility_highlights') {
        const items = Array.isArray(content.items) ? content.items : [];
        const isFacility = type === 'facility_highlights';
        return (
            <div className="grid gap-3">
                {' '}
                <div className="flex items-center justify-between">
                    {' '}
                    <span className="text-sm font-medium">Items</span>{' '}
                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => setField('items', [...items, isFacility ? { icon: 'CheckCircle2', text: '' } : { title: '', body: '' }])}
                    >
                        {' '}
                        <Plus className="size-3" /> Add Item{' '}
                    </Button>{' '}
                </div>{' '}
                {items.map((item: Record<string, any>, index: number) => (
                    <div key={index} className="bg-muted/30 rounded-md border p-3">
                        {' '}
                        <div className="flex items-start justify-between gap-2">
                            {' '}
                            <div className="flex items-center gap-2">
                                {' '}
                                <GripVertical className="text-muted-foreground/40 size-4" />{' '}
                                <span className="text-muted-foreground text-xs font-semibold uppercase">Item {index + 1}</span>{' '}
                            </div>{' '}
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() =>
                                    setField(
                                        'items',
                                        items.filter((_: any, i: number) => i !== index),
                                    )
                                }
                            >
                                {' '}
                                <Trash2 className="text-destructive size-3" />{' '}
                            </Button>{' '}
                        </div>{' '}
                        <div className="mt-3 grid gap-3">
                            {' '}
                            {isFacility ? (
                                <>
                                    {' '}
                                    <Field
                                        label="Icon Name"
                                        value={item.icon ?? 'CheckCircle2'}
                                        onChange={(value) => {
                                            const updated = [...items];
                                            updated[index] = { ...updated[index], icon: value };
                                            setField('items', updated);
                                        }}
                                    />{' '}
                                    <Field
                                        label="Text"
                                        value={item.text ?? ''}
                                        onChange={(value) => {
                                            const updated = [...items];
                                            updated[index] = { ...updated[index], text: value };
                                            setField('items', updated);
                                        }}
                                        multiline
                                    />{' '}
                                </>
                            ) : (
                                <>
                                    {' '}
                                    <Field
                                        label="Title"
                                        value={item.title ?? ''}
                                        onChange={(value) => {
                                            const updated = [...items];
                                            updated[index] = { ...updated[index], title: value };
                                            setField('items', updated);
                                        }}
                                    />{' '}
                                    <Field
                                        label="Body"
                                        value={item.body ?? ''}
                                        onChange={(value) => {
                                            const updated = [...items];
                                            updated[index] = { ...updated[index], body: value };
                                            setField('items', updated);
                                        }}
                                        multiline
                                    />{' '}
                                </>
                            )}{' '}
                        </div>{' '}
                    </div>
                ))}{' '}
            </div>
        );
    }
    if (type === 'stat_band') {
        const items = Array.isArray(content.items) ? content.items : [];
        return (
            <div className="grid gap-3">
                {' '}
                <div className="flex items-center justify-between">
                    {' '}
                    <span className="text-sm font-medium">Statistics</span>{' '}
                    <Button type="button" variant="outline" size="sm" onClick={() => setField('items', [...items, { value: '', label: '' }])}>
                        {' '}
                        <Plus className="size-3" /> Add Stat{' '}
                    </Button>{' '}
                </div>{' '}
                {items.map((item: Record<string, any>, index: number) => (
                    <div key={index} className="bg-muted/30 rounded-md border p-3">
                        {' '}
                        <div className="flex items-start justify-between gap-2">
                            {' '}
                            <div className="flex items-center gap-2">
                                {' '}
                                <GripVertical className="text-muted-foreground/40 size-4" />{' '}
                                <span className="text-muted-foreground text-xs font-semibold uppercase">Stat {index + 1}</span>{' '}
                            </div>{' '}
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() =>
                                    setField(
                                        'items',
                                        items.filter((_: any, i: number) => i !== index),
                                    )
                                }
                            >
                                {' '}
                                <Trash2 className="text-destructive size-3" />{' '}
                            </Button>{' '}
                        </div>{' '}
                        <div className="mt-3 grid gap-3 sm:grid-cols-2">
                            {' '}
                            <Field
                                label="Value"
                                value={item.value ?? ''}
                                onChange={(value) => {
                                    const updated = [...items];
                                    updated[index] = { ...updated[index], value };
                                    setField('items', updated);
                                }}
                            />{' '}
                            <Field
                                label="Label"
                                value={item.label ?? ''}
                                onChange={(value) => {
                                    const updated = [...items];
                                    updated[index] = { ...updated[index], label: value };
                                    setField('items', updated);
                                }}
                            />{' '}
                        </div>{' '}
                    </div>
                ))}{' '}
            </div>
        );
    }
    return null;
}
