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

type Asset = {
    id: number;
    kind: string;
    url: string;
    alt_text: string;
    credit: string | null;
};
type Story = {
    id: number;
    type: string;
    title: string;
    slug: string;
    excerpt: string | null;
    body: string | null;
    status: string;
    video_url: string | null;
    event_id: number | null;
    team_id: number | null;
    profile_id: number | null;
    assets: Asset[];
};
type PageRecord = {
    id: number;
    slug: string;
    title: string;
    body: string;
    meta_description: string | null;
    status: string;
    support_email: string | null;
    support_whatsapp: string | null;
};
type Option = {
    id: number;
    title?: string;
    name?: string;
    display_name?: string;
};
type StoryForm = {
    type: string;
    title: string;
    excerpt: string;
    body: string;
    status: string;
    event_id: string;
    team_id: string;
    profile_id: string;
    video_url: string;
    cover: File | null;
    cover_alt_text: string;
    cover_credit: string;
    images: File[];
    image_alt_texts: string[];
    image_credits: string[];
    remove_asset_ids: number[];
};

const blankStory: StoryForm = {
    type: 'news',
    title: '',
    excerpt: '',
    body: '',
    status: 'draft',
    event_id: '',
    team_id: '',
    profile_id: '',
    video_url: '',
    cover: null,
    cover_alt_text: '',
    cover_credit: '',
    images: [],
    image_alt_texts: [],
    image_credits: [],
    remove_asset_ids: [],
};

export default function ContentIndex({
    stories,
    pages,
    selectedStory,
    selectedPage,
    relatedOptions,
}: {
    stories: { data: Story[] };
    pages: PageRecord[];
    selectedStory: Story | null;
    selectedPage: PageRecord | null;
    relatedOptions: { events: Option[]; teams: Option[]; profiles: Option[] };
}) {
    const story = useForm<StoryForm>(
        selectedStory
            ? {
                  ...blankStory,
                  type: selectedStory.type,
                  title: selectedStory.title,
                  excerpt: selectedStory.excerpt || '',
                  body: selectedStory.body || '',
                  status: selectedStory.status,
                  event_id: selectedStory.event_id?.toString() || '',
                  team_id: selectedStory.team_id?.toString() || '',
                  profile_id: selectedStory.profile_id?.toString() || '',
                  video_url: selectedStory.video_url || '',
              }
            : blankStory,
    );
    const page = useForm({
        title: selectedPage?.title || '',
        body: selectedPage?.body || '',
        meta_description: selectedPage?.meta_description || '',
        status: selectedPage?.status || 'draft',
        support_email: selectedPage?.support_email || '',
        support_whatsapp: selectedPage?.support_whatsapp || '',
    });
    useEffect(() => {
        story.setData(
            selectedStory
                ? {
                      ...blankStory,
                      type: selectedStory.type,
                      title: selectedStory.title,
                      excerpt: selectedStory.excerpt || '',
                      body: selectedStory.body || '',
                      status: selectedStory.status,
                      event_id: selectedStory.event_id?.toString() || '',
                      team_id: selectedStory.team_id?.toString() || '',
                      profile_id: selectedStory.profile_id?.toString() || '',
                      video_url: selectedStory.video_url || '',
                  }
                : blankStory,
        );
    }, [selectedStory?.id]);
    useEffect(() => {
        page.setData({
            title: selectedPage?.title || '',
            body: selectedPage?.body || '',
            meta_description: selectedPage?.meta_description || '',
            status: selectedPage?.status || 'draft',
            support_email: selectedPage?.support_email || '',
            support_whatsapp: selectedPage?.support_whatsapp || '',
        });
    }, [selectedPage?.id]);

    const saveStory = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        if (selectedStory)
            story.patch(`/admin/content/stories/${selectedStory.id}`, {
                forceFormData: true,
                preserveScroll: true,
            });
        else
            story.post('/admin/content/stories', {
                forceFormData: true,
                preserveScroll: true,
            });
    };
    const savePage = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        if (selectedPage)
            page.put(`/admin/content/pages/${selectedPage.id}`, {
                preserveScroll: true,
            });
    };
    const chooseFile = (file: File | null) => story.setData('cover', file);
    const statusLabel = (status: string) =>
        status === 'published' ? 'Published' : 'Draft';

    return (
        <>
            <Head title="Content management" />
            <div className="mx-auto max-w-7xl space-y-6 p-4 md:p-8">
                <header className="flex flex-wrap items-end justify-between gap-4">
                    <div>
                        <p className="text-sm font-semibold text-muted-foreground">
                            Public site
                        </p>
                        <h1 className="text-3xl font-black tracking-tight">
                            Content desk
                        </h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Publish race stories and keep support information
                            current.
                        </p>
                    </div>
                    <Link
                        href="/admin/content"
                        className="rounded-xl bg-primary px-4 py-2.5 text-sm font-bold text-primary-foreground"
                    >
                        + New story
                    </Link>
                </header>
                <div className="grid gap-6 xl:grid-cols-[300px_minmax(0,1fr)]">
                    <aside className="space-y-5">
                        <section className="rounded-2xl border bg-card p-4">
                            <h2 className="font-black">Media stories</h2>
                            <div className="mt-3 space-y-2">
                                {stories.data.length ? (
                                    stories.data.map((item) => (
                                        <Link
                                            key={item.id}
                                            href={`/admin/content?story=${item.id}`}
                                            className={`block rounded-xl border p-3 ${selectedStory?.id === item.id ? 'border-primary bg-primary/5' : 'hover:bg-muted'}`}
                                        >
                                            <span className="flex items-center justify-between gap-2">
                                                <span className="truncate text-sm font-bold">
                                                    {item.title}
                                                </span>
                                                <span className="rounded-full bg-muted px-2 py-1 text-[10px] font-bold">
                                                    {statusLabel(item.status)}
                                                </span>
                                            </span>
                                            <span className="mt-1 block text-xs text-muted-foreground capitalize">
                                                {item.type.replace('_', ' ')}
                                            </span>
                                        </Link>
                                    ))
                                ) : (
                                    <p className="py-3 text-sm text-muted-foreground">
                                        No stories saved yet.
                                    </p>
                                )}
                            </div>
                        </section>
                        <section className="rounded-2xl border bg-card p-4">
                            <h2 className="font-black">Site pages</h2>
                            <p className="mt-1 text-xs text-muted-foreground">
                                Policies stay private until published.
                            </p>
                            <div className="mt-3 space-y-2">
                                {pages.map((item) => (
                                    <Link
                                        key={item.slug}
                                        href={`/admin/content?page=${item.slug}`}
                                        className={`flex items-center justify-between rounded-xl px-3 py-2.5 text-sm font-bold ${selectedPage?.slug === item.slug ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
                                    >
                                        <span>{item.title}</span>
                                        <span className="text-[10px] font-semibold opacity-70">
                                            {statusLabel(item.status)}
                                        </span>
                                    </Link>
                                ))}
                            </div>
                        </section>
                    </aside>
                    <div className="space-y-6">
                        <section className="rounded-2xl border bg-card p-5 sm:p-7">
                            <div className="flex flex-wrap items-start justify-between gap-3">
                                <div>
                                    <h2 className="text-xl font-black">
                                        {selectedStory
                                            ? 'Edit story'
                                            : 'Create a story'}
                                    </h2>
                                    <p className="mt-1 text-sm text-muted-foreground">
                                        Drafts are visible only to admins.
                                        Published stories appear in the media
                                        hub.
                                    </p>
                                </div>
                                {selectedStory && (
                                    <a
                                        href={`/admin/content/stories/${selectedStory.id}/preview`}
                                        target="_blank"
                                        rel="noreferrer"
                                        className="text-sm font-bold text-primary"
                                    >
                                        Preview story ↗
                                    </a>
                                )}
                            </div>
                            <form
                                onSubmit={saveStory}
                                className="mt-5 space-y-4"
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Content type
                                        <select
                                            value={story.data.type}
                                            onChange={(e) =>
                                                story.setData(
                                                    'type',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        >
                                            {[
                                                ['news', 'News'],
                                                ['race_report', 'Race report'],
                                                ['gallery', 'Photo gallery'],
                                                ['video', 'Video'],
                                            ].map(([key, label]) => (
                                                <option key={key} value={key}>
                                                    {label}
                                                </option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Publishing status
                                        <select
                                            value={story.data.status}
                                            onChange={(e) =>
                                                story.setData(
                                                    'status',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        >
                                            <option value="draft">
                                                Save as draft
                                            </option>
                                            <option value="published">
                                                Publish now
                                            </option>
                                        </select>
                                    </label>
                                </div>
                                <label className="grid gap-1.5 text-sm font-bold">
                                    Headline
                                    <input
                                        required
                                        maxLength={180}
                                        value={story.data.title}
                                        onChange={(e) =>
                                            story.setData(
                                                'title',
                                                e.target.value,
                                            )
                                        }
                                        className="rounded-xl border-input bg-background"
                                    />
                                </label>
                                <label className="grid gap-1.5 text-sm font-bold">
                                    Short summary
                                    <textarea
                                        rows={2}
                                        maxLength={500}
                                        value={story.data.excerpt}
                                        onChange={(e) =>
                                            story.setData(
                                                'excerpt',
                                                e.target.value,
                                            )
                                        }
                                        className="rounded-xl border-input bg-background"
                                    />
                                </label>
                                <label className="grid gap-1.5 text-sm font-bold">
                                    Story text
                                    <textarea
                                        rows={7}
                                        value={story.data.body}
                                        onChange={(e) =>
                                            story.setData(
                                                'body',
                                                e.target.value,
                                            )
                                        }
                                        className="rounded-xl border-input bg-background"
                                    />
                                </label>
                                {story.data.type === 'video' && (
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        YouTube or Vimeo link
                                        <input
                                            type="url"
                                            value={story.data.video_url}
                                            onChange={(e) =>
                                                story.setData(
                                                    'video_url',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                            placeholder="https://youtu.be/..."
                                        />
                                    </label>
                                )}
                                <div className="grid gap-4 sm:grid-cols-3">
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Related event
                                        <select
                                            value={story.data.event_id}
                                            onChange={(e) =>
                                                story.setData(
                                                    'event_id',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        >
                                            <option value="">None</option>
                                            {relatedOptions.events.map((o) => (
                                                <option key={o.id} value={o.id}>
                                                    {o.title}
                                                </option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Related team
                                        <select
                                            value={story.data.team_id}
                                            onChange={(e) =>
                                                story.setData(
                                                    'team_id',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        >
                                            <option value="">None</option>
                                            {relatedOptions.teams.map((o) => (
                                                <option key={o.id} value={o.id}>
                                                    {o.name}
                                                </option>
                                            ))}
                                        </select>
                                    </label>
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Related racer
                                        <select
                                            value={story.data.profile_id}
                                            onChange={(e) =>
                                                story.setData(
                                                    'profile_id',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        >
                                            <option value="">None</option>
                                            {relatedOptions.profiles.map(
                                                (o) => (
                                                    <option
                                                        key={o.id}
                                                        value={o.id}
                                                    >
                                                        {o.display_name}
                                                    </option>
                                                ),
                                            )}
                                        </select>
                                    </label>
                                </div>
                                <div className="grid gap-4 rounded-xl bg-muted/50 p-4 sm:grid-cols-2">
                                    <div className="space-y-3">
                                        <label className="grid gap-1.5 text-sm font-bold">
                                            Cover image
                                            <input
                                                type="file"
                                                accept="image/jpeg,image/png,image/webp"
                                                onChange={(e) =>
                                                    chooseFile(
                                                        e.target.files?.[0] ||
                                                            null,
                                                    )
                                                }
                                                className="text-xs"
                                            />
                                        </label>
                                        <input
                                            aria-label="Cover image alternative text"
                                            placeholder="Describe the cover image"
                                            value={story.data.cover_alt_text}
                                            onChange={(e) =>
                                                story.setData(
                                                    'cover_alt_text',
                                                    e.target.value,
                                                )
                                            }
                                            className="w-full rounded-lg border-input bg-background text-sm"
                                        />
                                        <input
                                            aria-label="Cover image credit"
                                            placeholder="Photographer / image credit"
                                            value={story.data.cover_credit}
                                            onChange={(e) =>
                                                story.setData(
                                                    'cover_credit',
                                                    e.target.value,
                                                )
                                            }
                                            className="w-full rounded-lg border-input bg-background text-sm"
                                        />
                                    </div>
                                    <div className="space-y-3">
                                        <label className="grid gap-1.5 text-sm font-bold">
                                            Gallery images
                                            <input
                                                type="file"
                                                accept="image/jpeg,image/png,image/webp"
                                                multiple
                                                onChange={(e) => {
                                                    const images = Array.from(
                                                        e.target.files || [],
                                                    );
                                                    story.setData((data) => ({
                                                        ...data,
                                                        images,
                                                        image_alt_texts:
                                                            images.map((file) =>
                                                                file.name.replace(
                                                                    /\\.[^.]+$/,
                                                                    '',
                                                                ),
                                                            ),
                                                        image_credits:
                                                            images.map(
                                                                () => '',
                                                            ),
                                                    }));
                                                }}
                                                className="text-xs"
                                            />
                                        </label>
                                        <p className="text-xs text-muted-foreground">
                                            Add descriptive alt text and
                                            photographer credit to each gallery
                                            image.
                                        </p>
                                    </div>
                                </div>
                                {story.data.images.length > 0 && (
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        {story.data.images.map(
                                            (image, index) => (
                                                <div
                                                    key={`${image.name}-${index}`}
                                                    className="grid gap-2 rounded-xl border p-3"
                                                >
                                                    <p className="truncate text-xs font-bold">
                                                        {image.name}
                                                    </p>
                                                    <input
                                                        aria-label={`Photo ${index + 1} alternative text`}
                                                        placeholder="Describe this photo"
                                                        value={
                                                            story.data
                                                                .image_alt_texts[
                                                                index
                                                            ] || ''
                                                        }
                                                        onChange={(e) =>
                                                            story.setData(
                                                                'image_alt_texts',
                                                                story.data.image_alt_texts.map(
                                                                    (
                                                                        value,
                                                                        i,
                                                                    ) =>
                                                                        i ===
                                                                        index
                                                                            ? e
                                                                                  .target
                                                                                  .value
                                                                            : value,
                                                                ),
                                                            )
                                                        }
                                                        className="rounded-lg border-input bg-background text-sm"
                                                    />
                                                    <input
                                                        aria-label={`Photo ${index + 1} credit`}
                                                        placeholder="Photographer / image credit"
                                                        value={
                                                            story.data
                                                                .image_credits[
                                                                index
                                                            ] || ''
                                                        }
                                                        onChange={(e) =>
                                                            story.setData(
                                                                'image_credits',
                                                                story.data.image_credits.map(
                                                                    (
                                                                        value,
                                                                        i,
                                                                    ) =>
                                                                        i ===
                                                                        index
                                                                            ? e
                                                                                  .target
                                                                                  .value
                                                                            : value,
                                                                ),
                                                            )
                                                        }
                                                        className="rounded-lg border-input bg-background text-sm"
                                                    />
                                                </div>
                                            ),
                                        )}
                                    </div>
                                )}
                                {selectedStory &&
                                    selectedStory.assets.length > 0 && (
                                        <div>
                                            <p className="text-sm font-bold">
                                                Current photos
                                            </p>
                                            <div className="mt-2 grid gap-3 sm:grid-cols-3">
                                                {selectedStory.assets.map(
                                                    (asset) => (
                                                        <label
                                                            key={asset.id}
                                                            className="overflow-hidden rounded-xl border bg-background text-xs"
                                                        >
                                                            <img
                                                                src={asset.url}
                                                                alt={
                                                                    asset.alt_text
                                                                }
                                                                className="aspect-video w-full object-cover"
                                                            />
                                                            <span className="flex items-center gap-2 p-2">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={story.data.remove_asset_ids.includes(
                                                                        asset.id,
                                                                    )}
                                                                    onChange={(
                                                                        e,
                                                                    ) =>
                                                                        story.setData(
                                                                            'remove_asset_ids',
                                                                            e
                                                                                .target
                                                                                .checked
                                                                                ? [
                                                                                      ...story
                                                                                          .data
                                                                                          .remove_asset_ids,
                                                                                      asset.id,
                                                                                  ]
                                                                                : story.data.remove_asset_ids.filter(
                                                                                      (
                                                                                          id,
                                                                                      ) =>
                                                                                          id !==
                                                                                          asset.id,
                                                                                  ),
                                                                        )
                                                                    }
                                                                />
                                                                <span className="truncate">
                                                                    Remove ·{' '}
                                                                    {asset.credit ||
                                                                        asset.alt_text}
                                                                </span>
                                                            </span>
                                                        </label>
                                                    ),
                                                )}
                                            </div>
                                        </div>
                                    )}
                                {Object.keys(story.errors).length > 0 && (
                                    <div
                                        role="alert"
                                        className="rounded-xl bg-destructive/10 p-3 text-sm text-destructive"
                                    >
                                        Check the highlighted story details and
                                        try again.
                                    </div>
                                )}
                                <button
                                    disabled={story.processing}
                                    className="rounded-xl bg-primary px-5 py-3 text-sm font-black text-primary-foreground disabled:opacity-50"
                                >
                                    {story.processing
                                        ? 'Saving…'
                                        : story.data.status === 'published'
                                          ? 'Save & publish'
                                          : 'Save draft'}
                                </button>
                            </form>
                        </section>
                        {selectedPage && (
                            <section className="rounded-2xl border bg-card p-5 sm:p-7">
                                <div className="flex flex-wrap items-start justify-between gap-3">
                                    <h2 className="text-xl font-black">
                                        {selectedPage.slug === 'support'
                                            ? 'Support information'
                                            : `${selectedPage.title} policy`}
                                    </h2>
                                    <p className="mt-1 text-sm text-muted-foreground">
                                        {selectedPage.slug === 'support'
                                            ? 'Contact information is shown on the public support page.'
                                            : 'Publish only after the wording has been reviewed and approved.'}
                                    </p>
                                    {selectedPage.slug !== 'support' && (
                                        <a
                                            href={`/admin/content/pages/${selectedPage.id}/preview`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="text-sm font-bold text-primary"
                                        >
                                            Preview page ↗
                                        </a>
                                    )}
                                </div>
                                <form
                                    onSubmit={savePage}
                                    className="mt-5 space-y-4"
                                >
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Page title
                                        <input
                                            required
                                            value={page.data.title}
                                            onChange={(e) =>
                                                page.setData(
                                                    'title',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        />
                                    </label>
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Public page text
                                        <textarea
                                            required
                                            rows={8}
                                            value={page.data.body}
                                            onChange={(e) =>
                                                page.setData(
                                                    'body',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        />
                                    </label>
                                    <label className="grid gap-1.5 text-sm font-bold">
                                        Search description
                                        <input
                                            value={page.data.meta_description}
                                            onChange={(e) =>
                                                page.setData(
                                                    'meta_description',
                                                    e.target.value,
                                                )
                                            }
                                            className="rounded-xl border-input bg-background"
                                        />
                                    </label>
                                    {selectedPage.slug === 'support' && (
                                        <div className="grid gap-4 sm:grid-cols-2">
                                            <label className="grid gap-1.5 text-sm font-bold">
                                                Support email
                                                <input
                                                    type="email"
                                                    value={
                                                        page.data.support_email
                                                    }
                                                    onChange={(e) =>
                                                        page.setData(
                                                            'support_email',
                                                            e.target.value,
                                                        )
                                                    }
                                                    className="rounded-xl border-input bg-background"
                                                />
                                            </label>
                                            <label className="grid gap-1.5 text-sm font-bold">
                                                WhatsApp number
                                                <input
                                                    value={
                                                        page.data
                                                            .support_whatsapp
                                                    }
                                                    onChange={(e) =>
                                                        page.setData(
                                                            'support_whatsapp',
                                                            e.target.value,
                                                        )
                                                    }
                                                    className="rounded-xl border-input bg-background"
                                                />
                                            </label>
                                        </div>
                                    )}
                                    {selectedPage.slug !== 'support' && (
                                        <label className="flex items-center gap-2 text-sm font-bold">
                                            <input
                                                type="checkbox"
                                                checked={
                                                    page.data.status ===
                                                    'published'
                                                }
                                                onChange={(e) =>
                                                    page.setData(
                                                        'status',
                                                        e.target.checked
                                                            ? 'published'
                                                            : 'draft',
                                                    )
                                                }
                                            />{' '}
                                            Publish this approved policy
                                        </label>
                                    )}
                                    <button
                                        disabled={page.processing}
                                        className="rounded-xl bg-primary px-5 py-3 text-sm font-black text-primary-foreground"
                                    >
                                        {page.processing
                                            ? 'Saving…'
                                            : 'Save page'}
                                    </button>
                                </form>
                            </section>
                        )}
                    </div>
                </div>
            </div>
        </>
    );
}
