import { Switch } from '@/Components/admin/fields';
import Avatar from '@/Components/shared/Avatar';
import Section from '@/Components/shared/Section';
import { Button } from '@/Components/ui/button';
import { Field, Input, Textarea } from '@/Components/ui/field';
import { cn } from '@/lib/utils';
import { PageProps } from '@/types';
import { Link, router, usePage } from '@inertiajs/react';
import { Upload } from 'lucide-react';
import { FormEventHandler, useRef, useState } from 'react';

export type ProfileData = { name: string; username: string | null; email: string; bio: string | null; avatar: string | null; platforms: number[]; activity_public: boolean };

export default function UpdateProfileInformationForm({ mustVerifyEmail, status, profile, platformOptions }: { mustVerifyEmail: boolean; status?: string; profile: ProfileData; platformOptions: { id: number; name: string }[] }) {
    const user = usePage<PageProps>().props.auth.user!;
    const fileRef = useRef<HTMLInputElement>(null);
    const [form, setForm] = useState({ name: profile.name, username: profile.username ?? '', email: profile.email, bio: profile.bio ?? '', platforms: profile.platforms, activity_public: profile.activity_public });
    const [avatar, setAvatar] = useState<File | null>(null);
    const [removeAvatar, setRemoveAvatar] = useState(false);
    const [errors, setErrors] = useState<Record<string, string>>({});
    const [processing, setProcessing] = useState(false);
    const [saved, setSaved] = useState(false);

    const preview = avatar ? URL.createObjectURL(avatar) : removeAvatar ? null : profile.avatar;

    const togglePlatform = (id: number) => setForm((f) => ({ ...f, platforms: f.platforms.includes(id) ? f.platforms.filter((p) => p !== id) : [...f.platforms, id] }));

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        router.post(
            route('profile.update'),
            { _method: 'patch', ...form, activity_public: form.activity_public ? 1 : 0, remove_avatar: removeAvatar ? 1 : 0, ...(avatar ? { avatar } : {}) },
            {
                forceFormData: true,
                preserveScroll: true,
                onStart: () => setProcessing(true),
                onError: (errs) => setErrors(errs),
                onSuccess: () => {
                    setErrors({});
                    setAvatar(null);
                    setRemoveAvatar(false);
                    setSaved(true);
                    setTimeout(() => setSaved(false), 2500);
                },
                onFinish: () => setProcessing(false),
            },
        );
    };

    return (
        <Section title="Profile information" description="How you appear on reviews and your library.">
            <form onSubmit={submit} className="space-y-5">
                <div className="flex items-center gap-4">
                    <Avatar name={form.name || user.name} src={preview} className="size-16 text-lg" />
                    <div className="space-y-1.5">
                        <div className="flex gap-2">
                            <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" id="avatar" onChange={(e) => { setAvatar(e.target.files?.[0] ?? null); setRemoveAvatar(false); }} />
                            <Button type="button" variant="secondary" size="sm" onClick={() => fileRef.current?.click()}><Upload /> Upload</Button>
                            {(preview) && <Button type="button" variant="ghost" size="sm" onClick={() => { setAvatar(null); setRemoveAvatar(true); }}>Remove</Button>}
                        </div>
                        <p className="text-xs text-muted-foreground">PNG, JPG or WebP, up to 2 MB.</p>
                        {errors.avatar && <p role="alert" className="text-xs text-destructive">{errors.avatar}</p>}
                    </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                    <Field label="Name" htmlFor="name" error={errors.name}><Input id="name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} autoComplete="name" /></Field>
                    <Field label="Username" htmlFor="username" error={errors.username}><Input id="username" value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} autoComplete="username" /></Field>
                </div>
                <Field label="Email" htmlFor="email" error={errors.email}><Input id="email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} autoComplete="email" /></Field>

                {mustVerifyEmail && !user.email_verified_at && (
                    <p className="text-sm text-muted-foreground">
                        Your email is unverified.{' '}
                        <Link href={route('verification.send')} method="post" as="button" className="font-medium text-foreground underline underline-offset-4">Resend verification email</Link>
                        {status === 'verification-link-sent' && <span className="ml-2 text-primary">Sent.</span>}
                    </p>
                )}

                <Field label="Bio" htmlFor="bio" error={errors.bio} hint={`${form.bio.length}/500`}>
                    <Textarea id="bio" rows={3} maxLength={500} value={form.bio} onChange={(e) => setForm({ ...form, bio: e.target.value })} placeholder="Tell people what you love to play." />
                </Field>

                <fieldset>
                    <legend className="mb-2 text-[13px] font-medium text-foreground/90">Preferred platforms</legend>
                    <div className="flex flex-wrap gap-2">
                        {platformOptions.map((p) => {
                            const on = form.platforms.includes(p.id);
                            return (
                                <button key={p.id} type="button" aria-pressed={on} onClick={() => togglePlatform(p.id)} className={cn('rounded-full border px-3 py-1.5 text-xs transition', on ? 'border-primary bg-primary/15 text-foreground' : 'border-border text-muted-foreground hover:text-foreground')}>
                                    {p.name}
                                </button>
                            );
                        })}
                    </div>
                    {errors.platforms && <p role="alert" className="mt-1 text-xs text-destructive">{errors.platforms}</p>}
                </fieldset>

                <Switch label="Share my activity with followers and on my public profile" checked={form.activity_public} onChange={(v) => setForm({ ...form, activity_public: v })} />

                <div className="flex items-center gap-3">
                    <Button type="submit" loading={processing}>Save changes</Button>
                    {saved && <span role="status" className="text-sm text-muted-foreground">Saved.</span>}
                </div>
            </form>
        </Section>
    );
}
