import { Head, Link, useForm } from '@inertiajs/react';

import { AdminLayout } from '@/layouts/admin-layout';

type Option = {
    value: string;
    label: string;
};

type SubjectOption = {
    id: number;
    label: string;
};

type AIContentCreateProps = {
    requestTypeOptions: Option[];
    subjectTypeOptions: Option[];
    productOptions: SubjectOption[];
    articleOptions: SubjectOption[];
    ollamaConfigured: boolean;
    defaultModel: string;
};

type AIContentForm = {
    request_type: string;
    subject_type: string;
    subject_id: string;
    custom_context: string;
};

export default function AIContentCreate({
    requestTypeOptions,
    subjectTypeOptions,
    productOptions,
    articleOptions,
    ollamaConfigured,
    defaultModel,
}: AIContentCreateProps) {
    const form = useForm<AIContentForm>({
        request_type: requestTypeOptions[0]?.value || 'blog_draft',
        subject_type: '',
        subject_id: '',
        custom_context: '',
    });

    const currentSubjectOptions =
        form.data.subject_type === 'product'
            ? productOptions
            : form.data.subject_type === 'blog_article'
              ? articleOptions
              : [];

    const setRequestType = (requestType: string) => {
        form.setData((data) => ({
            ...data,
            request_type: requestType,
            subject_type:
                requestType === 'product_description'
                    ? 'product'
                    : data.subject_type,
            subject_id:
                requestType === 'product_description' &&
                data.subject_type !== 'product'
                    ? ''
                    : data.subject_id,
        }));
    };

    const setSubjectType = (subjectType: string) => {
        form.setData((data) => ({
            ...data,
            subject_type: subjectType,
            subject_id: '',
        }));
    };

    const submit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        form.transform((data) => ({
            ...data,
            subject_type: data.subject_type === '' ? null : data.subject_type,
            subject_id: data.subject_id === '' ? null : Number(data.subject_id),
            custom_context:
                data.custom_context.trim() === ''
                    ? null
                    : data.custom_context.trim(),
        }));

        form.post('/admin/ai-content');
    };

    return (
        <AdminLayout>
            <Head title="Generate AI Content" />

            <div className="space-y-5">
                <div className="flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h1 className="text-2xl font-semibold text-[#0a1530] dark:text-[#efe8ff]">
                            Generate AI Content
                        </h1>
                        <p className="mt-1 text-sm text-slate-600 dark:text-[#c7bde8]">
                            Create a reviewable suggestion. Nothing is published
                            or applied automatically.
                        </p>
                    </div>
                    <Link
                        href="/admin/ai-content"
                        className="text-sm font-medium text-slate-600 hover:text-[#0a1530] dark:text-[#d7c7ff] dark:hover:text-[#efe8ff]"
                    >
                        Back to list
                    </Link>
                </div>

                {!ollamaConfigured ? (
                    <div className="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-800 dark:border-rose-400/40 dark:bg-rose-400/10 dark:text-rose-100">
                        Ollama is not configured. Set{' '}
                        <span className="font-semibold">OLLAMA_MODEL</span>{' '}
                        before generating content.
                    </div>
                ) : (
                    <div className="rounded-xl border border-sky-200 bg-sky-50 p-4 text-sm text-sky-900 dark:border-sky-400/40 dark:bg-sky-400/10 dark:text-sky-100">
                        Suggestions will be generated with{' '}
                        <span className="font-semibold">{defaultModel}</span>{' '}
                        and saved for human review.
                    </div>
                )}

                <form onSubmit={submit} className="space-y-5">
                    <div className="grid gap-4 lg:grid-cols-3">
                        <Field
                            label="Content Type"
                            error={form.errors.request_type}
                        >
                            <select
                                value={form.data.request_type}
                                onChange={(event) =>
                                    setRequestType(event.target.value)
                                }
                                className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-[#0a1530] outline-none focus:border-[#0b7285] dark:border-[#4a3a78] dark:bg-[#160f2d] dark:text-[#efe8ff] dark:focus:border-[#a78bfa]"
                            >
                                {requestTypeOptions.map((option) => (
                                    <option
                                        key={option.value}
                                        value={option.value}
                                    >
                                        {option.label}
                                    </option>
                                ))}
                            </select>
                        </Field>

                        <Field
                            label="Subject Type"
                            error={form.errors.subject_type}
                        >
                            <select
                                value={form.data.subject_type}
                                onChange={(event) =>
                                    setSubjectType(event.target.value)
                                }
                                disabled={
                                    form.data.request_type ===
                                    'product_description'
                                }
                                className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-[#0a1530] outline-none focus:border-[#0b7285] disabled:bg-slate-100 dark:border-[#4a3a78] dark:bg-[#160f2d] dark:text-[#efe8ff] dark:focus:border-[#a78bfa] dark:disabled:bg-[#241a45]"
                            >
                                <option value="">No saved subject</option>
                                {subjectTypeOptions.map((option) => (
                                    <option
                                        key={option.value}
                                        value={option.value}
                                    >
                                        {option.label}
                                    </option>
                                ))}
                            </select>
                        </Field>

                        <Field label="Subject" error={form.errors.subject_id}>
                            <select
                                value={form.data.subject_id}
                                onChange={(event) =>
                                    form.setData(
                                        'subject_id',
                                        event.target.value,
                                    )
                                }
                                disabled={form.data.subject_type === ''}
                                className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-[#0a1530] outline-none focus:border-[#0b7285] disabled:bg-slate-100 dark:border-[#4a3a78] dark:bg-[#160f2d] dark:text-[#efe8ff] dark:focus:border-[#a78bfa] dark:disabled:bg-[#241a45]"
                            >
                                <option value="">Select a subject</option>
                                {currentSubjectOptions.map((option) => (
                                    <option
                                        key={option.id}
                                        value={String(option.id)}
                                    >
                                        {option.label}
                                    </option>
                                ))}
                            </select>
                        </Field>
                    </div>

                    <Field
                        label="Additional Context"
                        error={form.errors.custom_context}
                    >
                        <textarea
                            value={form.data.custom_context}
                            onChange={(event) =>
                                form.setData(
                                    'custom_context',
                                    event.target.value,
                                )
                            }
                            rows={9}
                            placeholder="Add topic, target keywords, product notes, fitment cautions, tone, or article outline. Required when no saved product/article is selected."
                            className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-[#0a1530] outline-none focus:border-[#0b7285] dark:border-[#4a3a78] dark:bg-[#160f2d] dark:text-[#efe8ff] dark:focus:border-[#a78bfa]"
                        />
                    </Field>

                    <div className="rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700 dark:border-[#3c2b68] dark:bg-[#160f2d] dark:text-[#c7bde8]">
                        The generated result will be stored as an AI suggestion
                        with its prompt and context snapshot. Supported fields
                        can be applied only after human review.
                    </div>

                    <button
                        type="submit"
                        disabled={form.processing || !ollamaConfigured}
                        className="rounded-lg bg-[#0b7285] px-4 py-2 text-sm font-semibold text-white hover:bg-[#095f6f] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-[#7c3aed] dark:hover:bg-[#8b5cf6]"
                    >
                        Generate Review Draft
                    </button>
                </form>
            </div>
        </AdminLayout>
    );
}

function Field({
    label,
    error,
    children,
}: {
    label: string;
    error?: string;
    children: React.ReactNode;
}) {
    return (
        <div>
            <label className="block text-sm font-medium text-[#0a1530] dark:text-[#e5dcff]">
                {label}
            </label>
            <div className="mt-1">{children}</div>
            {error ? (
                <p className="mt-1 text-xs text-rose-600">{error}</p>
            ) : null}
        </div>
    );
}
