import { Form, Head, usePage, router } from '@inertiajs/react';
import { Link } from '@inertiajs/react';
import { useRef } from 'react';
import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController';
import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController';
import DeleteUser from '@/components/delete-user';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { edit } from '@/routes/profile';
import { send } from '@/routes/verification';
import type { Auth, BreadcrumbItem } from '@/types';
import AppLayout from '@/layouts/app-layout';
import { cn } from '@/lib/utils';
import { User, Mail, Phone, Info, Award, Settings, Lock, Camera } from 'lucide-react';

type PageProps = {
    auth: Auth;
};

const UI_THEMES = [
    { value: 'umum', label: 'Umum', desc: 'Pelajar umum' },
    { value: 'siswa', label: 'Siswa', desc: 'Pelajar SMP/SMA' },
    { value: 'mahasiswa', label: 'Mahasiswa', desc: 'Perguruan tinggi' },
    { value: 'profesional', label: 'Profesional', desc: 'Pekerja profesional' },
    { value: 'pengusaha', label: 'Pengusaha', desc: 'Pemilik bisnis' },
    { value: 'pensiunan', label: 'Pensiunan', desc: 'Masa purnabakti' },
] as const;

export default function Profile({
    mustVerifyEmail,
    status,
    passwordRules,
}: {
    mustVerifyEmail: boolean;
    status?: string;
    passwordRules: string;
}) {
    const { auth } = usePage<PageProps>().props;
    const passwordInput = useRef<HTMLInputElement>(null);
    const currentPasswordInput = useRef<HTMLInputElement>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('avatar', file);

        router.post('/settings/profile/avatar', formData, {
            preserveScroll: true,
        });
    };

    return (
        <>
            <Head title="Pengaturan Profil" />

            <div className="px-4 py-6 space-y-8">
                <Heading
                    title="Pengaturan Profil"
                    description="Kelola informasi profil dan keamanan akun Anda"
                />
                <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-6 space-y-6">
                    <div>
                        <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                            <Settings className="h-5 w-5 text-emerald-600" />
                            Informasi Profil
                        </h2>
                        <p className="text-xs text-gray-400 mt-0.5">Perbarui nama, email, nomor telepon, dan data pribadi Anda</p>
                    </div>

                    <div className="flex flex-col items-center gap-4 py-4 sm:flex-row sm:gap-6 bg-sky-50/60 rounded-2xl p-4 border border-sky-100">
                        <div className="relative group cursor-pointer" onClick={() => fileInputRef.current?.click()}>
                            <div className="size-24 rounded-full border-4 border-white shadow-md overflow-hidden bg-sky-100/70 flex items-center justify-center transition-transform hover:scale-105 duration-300">
                                {auth.user.avatar ? (
                                    <img
                                        src={auth.user.avatar}
                                        alt={auth.user.name}
                                        className="size-full object-cover"
                                    />
                                ) : (
                                    <span className="text-2xl font-bold text-sky-600/90">
                                        {auth.user.name.charAt(0).toUpperCase()}
                                    </span>
                                )}
                            </div>
                            <div className="absolute bottom-0 right-0 p-1.5 bg-white rounded-full shadow-md border border-sky-100 text-sky-600 transition-colors group-hover:bg-sky-50">
                                <Camera className="size-4" />
                            </div>
                        </div>

                        <div className="text-center sm:text-left space-y-1.5">
                            <h3 className="text-sm font-bold text-sky-900">Foto Profil</h3>
                            <p className="text-xs text-sky-600/70 leading-relaxed max-w-xs">
                                Gunakan foto berformat JPG, PNG, atau GIF dengan ukuran maksimal 2MB untuk hasil terbaik.
                            </p>
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                className="rounded-xl border-sky-200 text-sky-700 bg-white hover:bg-sky-50 font-medium text-xs mt-1 shadow-sm"
                                onClick={() => fileInputRef.current?.click()}
                            >
                                Pilih Foto Baru
                            </Button>
                            <input
                                type="file"
                                ref={fileInputRef}
                                className="hidden"
                                accept="image/*"
                                onChange={handleAvatarUpload}
                            />
                        </div>
                    </div>

                    <Form
                        {...ProfileController.update.form()}
                        options={{
                            preserveScroll: true,
                        }}
                        className="space-y-5"
                    >
                        {({ processing, errors }) => (
                            <>
                                <div className="grid gap-2">
                                    <Label htmlFor="name" className="text-xs font-semibold text-gray-700">Nama Lengkap</Label>
                                    <div className="relative">
                                        <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                                            <User className="h-4 w-4 text-gray-400" />
                                        </div>
                                        <Input
                                            id="name"
                                            className="pl-9 block w-full rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                            defaultValue={auth.user.name}
                                            name="name"
                                            required
                                            autoComplete="name"
                                            placeholder="Nama lengkap"
                                        />
                                    </div>
                                    <InputError className="mt-1" message={errors.name} />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="email" className="text-xs font-semibold text-gray-700">Alamat Email</Label>
                                    <div className="relative">
                                        <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                                            <Mail className="h-4 w-4 text-gray-400" />
                                        </div>
                                        <Input
                                            id="email"
                                            type="email"
                                            className="pl-9 block w-full rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                            defaultValue={auth.user.email}
                                            name="email"
                                            required
                                            autoComplete="username"
                                            placeholder="Alamat email"
                                        />
                                    </div>
                                    <InputError className="mt-1" message={errors.email} />
                                </div>

                                {mustVerifyEmail && auth.user.email_verified_at === null && (
                                    <div className="rounded-xl bg-amber-50 border border-amber-100 p-3.5">
                                        <p className="text-xs text-amber-800">
                                            Email Anda belum diverifikasi.{' '}
                                            <Link
                                                href={send()}
                                                as="button"
                                                className="font-bold underline hover:text-amber-950 transition-colors"
                                            >
                                                Kirim ulang email verifikasi.
                                            </Link>
                                        </p>
                                        {status === 'verification-link-sent' && (
                                            <div className="mt-1.5 text-xs font-semibold text-emerald-700">
                                                Tautan verifikasi baru telah dikirim ke email Anda.
                                            </div>
                                        )}
                                    </div>
                                )}

                                <div className="grid gap-2">
                                    <Label htmlFor="phone" className="text-xs font-semibold text-gray-700">Nomor Telepon</Label>
                                    <div className="relative">
                                        <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                                            <Phone className="h-4 w-4 text-gray-400" />
                                        </div>
                                        <Input
                                            id="phone"
                                            type="tel"
                                            inputMode="numeric"
                                            className="pl-9 block w-full rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                            defaultValue={auth.user.phone ?? ''}
                                            name="phone"
                                            autoComplete="tel"
                                            placeholder="Contoh: 08123456789"
                                            onInput={(e) => {
                                                const el = e.currentTarget;
                                                el.value = el.value.replace(/[^0-9+\-\s()]/g, '');
                                            }}
                                        />
                                    </div>
                                    <InputError className="mt-1" message={errors.phone} />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="bio" className="text-xs font-semibold text-gray-700">Bio</Label>
                                    <textarea
                                        id="bio"
                                        name="bio"
                                        rows={3}
                                        defaultValue={auth.user.bio ?? ''}
                                        placeholder="Ceritakan sedikit tentang diri Anda..."
                                        className="w-full text-sm rounded-xl border border-gray-200 bg-transparent px-3 py-2 shadow-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500 placeholder:text-gray-400"
                                    />
                                    <InputError className="mt-1" message={errors.bio} />
                                </div>

                                <div className="grid gap-3 pt-2">
                                    <div>
                                        <Label className="text-xs font-semibold text-gray-700">Kategori Pengguna</Label>
                                        <p className="text-[11px] text-gray-400">
                                            Pilih kategori untuk personalisasi pengalaman belajar Anda
                                        </p>
                                    </div>
                                    
                                    <div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3">
                                        {UI_THEMES.map((theme) => (
                                            <label
                                                key={theme.value}
                                                className="relative flex flex-col justify-center cursor-pointer rounded-xl border border-gray-200 p-3.5 transition-all hover:bg-gray-50/50 has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/40"
                                            >
                                                <input
                                                    type="radio"
                                                    name="ui_theme"
                                                    value={theme.value}
                                                    defaultChecked={auth.user.ui_theme === theme.value}
                                                    className="sr-only"
                                                />
                                                <span className="font-semibold text-xs text-gray-800 checked:text-emerald-900">{theme.label}</span>
                                                <span className="text-[10px] text-gray-400 mt-0.5 leading-tight">{theme.desc}</span>
                                            </label>
                                        ))}
                                    </div>
                                    <InputError className="mt-1" message={errors.ui_theme} />
                                </div>

                                <div className="flex justify-end pt-2">
                                    <Button
                                        disabled={processing}
                                        className="rounded-xl bg-emerald-600 hover:bg-emerald-700 font-semibold px-6"
                                        data-test="update-profile-button"
                                    >
                                        Simpan Perubahan
                                    </Button>
                                </div>
                            </>
                        )}
                    </Form>
                </div>

                <div className="bg-white rounded-3xl border border-gray-100 shadow-sm p-6 space-y-6">
                    <div>
                        <h2 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                            <Lock className="h-5 w-5 text-emerald-600" />
                            Keamanan Akun
                        </h2>
                        <p className="text-xs text-gray-400 mt-0.5">Perbarui kata sandi Anda untuk memastikan akun tetap aman</p>
                    </div>

                    <Form
                        {...SecurityController.update.form()}
                        options={{
                            preserveScroll: true,
                        }}
                        resetOnError={[
                            'password',
                            'password_confirmation',
                            'current_password',
                        ]}
                        resetOnSuccess
                        onError={(errors) => {
                            if (errors.password) {
                                passwordInput.current?.focus();
                            }

                            if (errors.current_password) {
                                currentPasswordInput.current?.focus();
                            }
                        }}
                        className="space-y-5"
                    >
                        {({ errors, processing }) => (
                            <>
                                <div className="grid gap-2">
                                    <Label htmlFor="current_password" className="text-xs font-semibold text-gray-700">
                                        Kata Sandi Saat Ini
                                    </Label>
                                    <PasswordInput
                                        id="current_password"
                                        ref={currentPasswordInput}
                                        name="current_password"
                                        className="rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                        autoComplete="current-password"
                                        placeholder="Kata sandi saat ini"
                                    />
                                    <InputError message={errors.current_password} />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="password" className="text-xs font-semibold text-gray-700">
                                        Kata Sandi Baru
                                    </Label>
                                    <PasswordInput
                                        id="password"
                                        ref={passwordInput}
                                        name="password"
                                        className="rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                        autoComplete="new-password"
                                        placeholder="Kata sandi baru"
                                        passwordrules={passwordRules}
                                    />
                                    <InputError message={errors.password} />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="password_confirmation" className="text-xs font-semibold text-gray-700">
                                        Konfirmasi Kata Sandi Baru
                                    </Label>
                                    <PasswordInput
                                        id="password_confirmation"
                                        name="password_confirmation"
                                        className="rounded-xl border-gray-200 focus-visible:ring-emerald-500/20 focus-visible:border-emerald-500"
                                        autoComplete="new-password"
                                        placeholder="Konfirmasi kata sandi baru"
                                        passwordrules={passwordRules}
                                    />
                                    <InputError message={errors.password_confirmation} />
                                </div>

                                <div className="flex justify-end pt-2">
                                    <Button
                                        disabled={processing}
                                        className="rounded-xl bg-emerald-600 hover:bg-emerald-700 font-semibold px-6"
                                        data-test="update-password-button"
                                    >
                                        Perbarui Kata Sandi
                                    </Button>
                                </div>
                            </>
                        )}
                    </Form>
                </div>

                <div className="bg-white rounded-3xl border border-red-100 shadow-sm p-6">
                    <DeleteUser />
                </div>
            </div>
        </>
    );
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Pengaturan Profil',
        href: edit(),
    },
];

Profile.layout = (page: React.ReactNode) => (
    <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>
);
