import { RichTextEditor } from '@/components/admin/RichTextEditor';
import { ImageUploader } from '@/components/ImageUploader';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import AdminLayout from '@/Layouts/AdminLayout';
import { cn } from '@/lib/utils';
import type { ArticleType } from '@/types/platform';
import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Newspaper, Radio, Save } from 'lucide-react';

// ── Types ─────────────────────────────────────────────────────────────────────

interface ArticleData {
    id: string;
    type: ArticleType;
    title: string;
    slug: string;
    excerpt: string | null;
    body: string | null;
    category: string | null;
    tags: string;
    published_at: string | null;
    status: string;
    cover_url: string | null;
    created_at: string;
    outlet?: string | null;
    company?: string | null;
    location?: string | null;
    clients?: string | null;
    read_time?: string | null;
    results?: string;
    level?: string | null;
    duration?: string | null;
    format?: string | null;
    icon?: string | null;
}

interface Props {
    article?: ArticleData;
}

const TYPE_OPTIONS: { value: ArticleType; label: string }[] = [
    { value: 'news', label: 'News' },
    { value: 'case_study', label: 'Case Study' },
    { value: 'tutorial', label: 'Tutorial' },
    { value: 'help_article', label: 'Help Article' },
];

const TYPE_DETAILS_LABEL: Record<ArticleType, string> = {
    news: 'News details',
    case_study: 'Case study details',
    tutorial: 'Tutorial details',
    help_article: 'Help article details',
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function Field({
    label,
    error,
    hint,
    children,
}: {
    label: string;
    error?: string;
    hint?: string;
    children: React.ReactNode;
}) {
    return (
        <div className="space-y-1.5">
            <label className="text-muted-foreground block text-xs font-semibold tracking-wide uppercase">
                {label}
            </label>
            {children}
            {hint && !error && (
                <p className="text-muted-foreground text-xs">{hint}</p>
            )}
            {error && <p className="text-destructive text-xs">{error}</p>}
        </div>
    );
}

function Card({
    title,
    children,
}: {
    title: string;
    children: React.ReactNode;
}) {
    return (
        <div className="pf-glass space-y-5 rounded-xl p-6">
            <p className="text-muted-foreground dark:text-muted-foreground/50 text-[10px] font-bold tracking-widest uppercase">
                {title}
            </p>
            {children}
        </div>
    );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function ArticleForm({ article }: Props) {
    const isEdit = !!article;

    const { data, setData, post, put, processing, errors } = useForm({
        type: article?.type ?? ('news' as ArticleType),
        title: article?.title ?? '',
        slug: article?.slug ?? '',
        excerpt: article?.excerpt ?? '',
        body: article?.body ?? '',
        category: article?.category ?? '',
        tags: article?.tags ?? '',
        published_at: article?.published_at
            ? article.published_at.substring(0, 16)
            : '',
        cover: null as File | null,
        remove_cover: false,
        outlet: article?.outlet ?? '',
        company: article?.company ?? '',
        location: article?.location ?? '',
        clients: article?.clients ?? '',
        read_time: article?.read_time ?? '',
        results: article?.results ?? '',
        level: article?.level ?? '',
        duration: article?.duration ?? '',
        format: article?.format ?? '',
        icon: article?.icon ?? '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (isEdit) {
            put(`/admin/articles/${article.id}`);
        } else {
            post('/admin/articles');
        }
    };

    return (
        <AdminLayout
            title={isEdit ? 'Edit Article' : 'New Article'}
            breadcrumbs={[
                { label: 'Articles', href: '/admin/articles' },
                { label: isEdit ? 'Edit' : 'New' },
            ]}
        >
            <Head title={isEdit ? 'Edit Article' : 'New Article'} />

            <form onSubmit={handleSubmit} className="p-6 lg:p-8">
                <div className="mb-6 flex items-center gap-3">
                    <Link
                        href="/admin/articles"
                        className="border-border text-muted-foreground hover:bg-muted/40 hover:text-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors"
                    >
                        <ArrowLeft className="h-4 w-4" />
                    </Link>
                    <Newspaper className="text-primary h-5 w-5" />
                    <h1 className="text-foreground text-lg font-bold">
                        {isEdit ? 'Edit Article' : 'New Article'}
                    </h1>
                </div>

                <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_360px]">
                    {/* ── Main column ──────────────────────────────────────── */}
                    <div className="flex flex-col gap-6">
                        <Card title="Content">
                            <Field label="Title" error={errors.title}>
                                <Input
                                    value={data.title}
                                    onChange={(e) => {
                                        setData('title', e.target.value);
                                        if (!isEdit) {
                                            setData(
                                                'slug',
                                                e.target.value
                                                    .toLowerCase()
                                                    .trim()
                                                    .replace(/[^a-z0-9]+/g, '-')
                                                    .replace(/(^-|-$)/g, ''),
                                            );
                                        }
                                    }}
                                    placeholder="Article title"
                                    className={cn(
                                        'text-base font-semibold',
                                        errors.title && 'border-destructive',
                                    )}
                                />
                            </Field>

                            <Field label="Slug" error={errors.slug}>
                                <Input
                                    value={data.slug}
                                    onChange={(e) =>
                                        setData('slug', e.target.value)
                                    }
                                    placeholder="article-slug"
                                    className={cn(
                                        errors.slug && 'border-destructive',
                                    )}
                                />
                            </Field>

                            <Field label="Excerpt" error={errors.excerpt}>
                                <Textarea
                                    value={data.excerpt}
                                    onChange={(e) =>
                                        setData('excerpt', e.target.value)
                                    }
                                    rows={3}
                                    placeholder="Short summary shown on the card"
                                    className={cn(
                                        'resize-y',
                                        errors.excerpt && 'border-destructive',
                                    )}
                                />
                            </Field>
                        </Card>

                        <Card title="Body">
                            <RichTextEditor
                                value={data.body}
                                onChange={(html) => setData('body', html)}
                                placeholder="Write the full article…"
                            />
                        </Card>
                    </div>

                    {/* ── Sidebar ──────────────────────────────────────────── */}
                    <div className="flex flex-col gap-6">
                        <Card title="Publish">
                            <Field
                                label="Publish date"
                                error={errors.published_at}
                                hint="Leave blank to save as draft. Set a future time to schedule."
                            >
                                <Input
                                    type="datetime-local"
                                    value={data.published_at}
                                    onChange={(e) =>
                                        setData('published_at', e.target.value)
                                    }
                                    className={cn(
                                        errors.published_at &&
                                            'border-destructive',
                                    )}
                                />
                            </Field>

                            <div className="flex flex-col gap-2 pt-1">
                                <Button
                                    type="submit"
                                    disabled={processing}
                                    className="w-full gap-2"
                                >
                                    {data.published_at ? (
                                        <>
                                            <Radio className="h-3.5 w-3.5" />
                                            {isEdit ? 'Update' : 'Publish'}
                                        </>
                                    ) : (
                                        <>
                                            <Save className="h-3.5 w-3.5" />
                                            Save draft
                                        </>
                                    )}
                                </Button>
                                {data.published_at && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        disabled={processing}
                                        className="w-full"
                                        onClick={() => {
                                            setData('published_at', '');
                                            setTimeout(() => {
                                                (
                                                    document.querySelector(
                                                        'form',
                                                    ) as HTMLFormElement
                                                )?.requestSubmit();
                                            }, 0);
                                        }}
                                    >
                                        Save as draft
                                    </Button>
                                )}
                                <Link
                                    href="/admin/articles"
                                    className="text-muted-foreground hover:text-foreground py-1 text-center text-sm transition-colors"
                                >
                                    Cancel
                                </Link>
                            </div>
                        </Card>

                        <Card title="Type & organization">
                            <Field label="Type">
                                <Select
                                    value={data.type}
                                    onValueChange={(v) =>
                                        setData('type', v as ArticleType)
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {TYPE_OPTIONS.map((o) => (
                                            <SelectItem
                                                key={o.value}
                                                value={o.value}
                                            >
                                                {o.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Field>

                            {data.type !== 'news' && (
                                <Field
                                    label={
                                        data.type === 'case_study'
                                            ? 'Tag'
                                            : 'Category'
                                    }
                                >
                                    <Input
                                        value={data.category}
                                        onChange={(e) =>
                                            setData('category', e.target.value)
                                        }
                                        placeholder={
                                            data.type === 'case_study'
                                                ? 'e.g. Loan Management'
                                                : 'e.g. Loans'
                                        }
                                    />
                                </Field>
                            )}

                            <Field
                                label="Tags"
                                hint="Separate multiple tags with commas."
                            >
                                <Input
                                    value={data.tags}
                                    onChange={(e) =>
                                        setData('tags', e.target.value)
                                    }
                                    placeholder="e.g. billing, mobile, api"
                                />
                            </Field>
                        </Card>

                        <Card title="Cover image">
                            <ImageUploader
                                url={
                                    data.cover
                                        ? null
                                        : (article?.cover_url ?? null)
                                }
                                name={data.title || 'Article cover'}
                                cropShape="rect"
                                onSelect={(file) => {
                                    setData('cover', file);
                                    setData('remove_cover', !file);
                                }}
                            />
                        </Card>

                        <Card title={TYPE_DETAILS_LABEL[data.type]}>
                            {data.type === 'news' && (
                                <Field label="Outlet">
                                    <Input
                                        value={data.outlet}
                                        onChange={(e) =>
                                            setData('outlet', e.target.value)
                                        }
                                        placeholder="e.g. TechCrunch"
                                    />
                                </Field>
                            )}

                            {data.type === 'case_study' && (
                                <>
                                    <Field label="Company">
                                        <Input
                                            value={data.company}
                                            onChange={(e) =>
                                                setData(
                                                    'company',
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </Field>
                                    <Field label="Location">
                                        <Input
                                            value={data.location}
                                            onChange={(e) =>
                                                setData(
                                                    'location',
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </Field>
                                    <div className="grid grid-cols-2 gap-3">
                                        <Field label="Clients">
                                            <Input
                                                value={data.clients}
                                                onChange={(e) =>
                                                    setData(
                                                        'clients',
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </Field>
                                        <Field label="Read time">
                                            <Input
                                                value={data.read_time}
                                                onChange={(e) =>
                                                    setData(
                                                        'read_time',
                                                        e.target.value,
                                                    )
                                                }
                                                placeholder="e.g. 4 min"
                                            />
                                        </Field>
                                    </div>
                                    <Field
                                        label="Results"
                                        hint="One result per line."
                                    >
                                        <Textarea
                                            value={data.results}
                                            onChange={(e) =>
                                                setData(
                                                    'results',
                                                    e.target.value,
                                                )
                                            }
                                            rows={3}
                                            className="resize-y"
                                        />
                                    </Field>
                                </>
                            )}

                            {data.type === 'tutorial' && (
                                <>
                                    <div className="grid grid-cols-2 gap-3">
                                        <Field label="Level">
                                            <Select
                                                value={data.level}
                                                onValueChange={(v) =>
                                                    setData('level', v)
                                                }
                                            >
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Select" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="Beginner">
                                                        Beginner
                                                    </SelectItem>
                                                    <SelectItem value="Intermediate">
                                                        Intermediate
                                                    </SelectItem>
                                                    <SelectItem value="Advanced">
                                                        Advanced
                                                    </SelectItem>
                                                </SelectContent>
                                            </Select>
                                        </Field>
                                        <Field label="Format">
                                            <Select
                                                value={data.format}
                                                onValueChange={(v) =>
                                                    setData('format', v)
                                                }
                                            >
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Select" />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value="Video">
                                                        Video
                                                    </SelectItem>
                                                    <SelectItem value="Guide">
                                                        Guide
                                                    </SelectItem>
                                                </SelectContent>
                                            </Select>
                                        </Field>
                                    </div>
                                    <div className="grid grid-cols-2 gap-3">
                                        <Field label="Duration">
                                            <Input
                                                value={data.duration}
                                                onChange={(e) =>
                                                    setData(
                                                        'duration',
                                                        e.target.value,
                                                    )
                                                }
                                                placeholder="e.g. 8 min"
                                            />
                                        </Field>
                                        <Field label="Icon key">
                                            <Input
                                                value={data.icon}
                                                onChange={(e) =>
                                                    setData(
                                                        'icon',
                                                        e.target.value,
                                                    )
                                                }
                                                placeholder="e.g. CreditCard"
                                            />
                                        </Field>
                                    </div>
                                </>
                            )}

                            {data.type === 'help_article' && (
                                <Field label="Icon key">
                                    <Input
                                        value={data.icon}
                                        onChange={(e) =>
                                            setData('icon', e.target.value)
                                        }
                                        placeholder="e.g. LifeBuoy"
                                    />
                                </Field>
                            )}
                        </Card>
                    </div>
                </div>
            </form>
        </AdminLayout>
    );
}
