import { Head, router, usePage } from '@inertiajs/react';
import { PasswordInput } from '@ui/components/password-input';
import { Button } from '@ui/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@ui/components/ui/card';
import { Input } from '@ui/components/ui/input';
import { Label } from '@ui/components/ui/label';
import { Separator } from '@ui/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@ui/components/ui/tabs';
import { KeyRound, Loader2, User } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { FinanceAppLayout } from '@/layouts/finance-app-layout';

interface ProfilePageProps {
    title?: string;
    user: {
        name: string;
        email: string;
    };
}

export default function ProfileSettings({ title, user }: ProfilePageProps) {
    const { errors } = usePage<{ errors: Record<string, string> }>().props;

    // Profile form state
    const [profileName, setProfileName] = useState(user.name);
    const [isUpdatingProfile, setIsUpdatingProfile] = useState(false);

    // Password form state
    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [isUpdatingPassword, setIsUpdatingPassword] = useState(false);

    const handleProfileSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        router.patch('/settings/profile', { name: profileName }, {
            preserveScroll: true,
            onStart: () => setIsUpdatingProfile(true),
            onSuccess: () => {
                toast.success('Profil berhasil diperbarui.');
            },
            onError: (errs) => {
                const first = Object.values(errs)[0];
                toast.error(first || 'Terjadi kesalahan.');
            },
            onFinish: () => setIsUpdatingProfile(false),
        });
    };

    const handlePasswordSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (newPassword !== confirmPassword) {
            toast.error('Konfirmasi password tidak cocok.');

            return;
        }

        router.patch('/settings/password', {
            current_password: currentPassword,
            password: newPassword,
            password_confirmation: confirmPassword,
        }, {
            preserveScroll: true,
            onStart: () => setIsUpdatingPassword(true),
            onSuccess: () => {
                toast.success('Password berhasil diperbarui.');
                setCurrentPassword('');
                setNewPassword('');
                setConfirmPassword('');
            },
            onError: (errs) => {
                const first = Object.values(errs)[0];
                toast.error(first || 'Terjadi kesalahan. Periksa password Anda.');
            },
            onFinish: () => setIsUpdatingPassword(false),
        });
    };

    return (
        <FinanceAppLayout>
            <Head title={title || 'Pengaturan Profil'} />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6 max-w-2xl">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight text-foreground">Pengaturan Akun</h1>
                    <p className="text-muted-foreground">Kelola informasi profil dan keamanan akun Anda.</p>
                </div>

                <Tabs defaultValue="profile">
                    <TabsList className="grid w-full grid-cols-2">
                        <TabsTrigger value="profile" className="gap-2">
                            <User className="h-4 w-4" />
                            Profil
                        </TabsTrigger>
                        <TabsTrigger value="password" className="gap-2">
                            <KeyRound className="h-4 w-4" />
                            Ganti Password
                        </TabsTrigger>
                    </TabsList>

                    {/* ── Profile Tab ── */}
                    <TabsContent value="profile" className="mt-4">
                        <Card>
                            <CardHeader>
                                <CardTitle>Informasi Profil</CardTitle>
                                <CardDescription>
                                    Perbarui nama tampilan akun Anda.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <form onSubmit={handleProfileSubmit} className="space-y-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="name">Nama</Label>
                                        <Input
                                            id="name"
                                            value={profileName}
                                            onChange={(e) => setProfileName(e.target.value)}
                                            placeholder="Nama lengkap"
                                            required
                                        />
                                        {errors.name && (
                                            <p className="text-sm text-destructive">{errors.name}</p>
                                        )}
                                    </div>

                                    <div className="space-y-2">
                                        <Label htmlFor="email">Email</Label>
                                        <Input
                                            id="email"
                                            value={user.email}
                                            readOnly
                                            disabled
                                            className="bg-muted cursor-not-allowed"
                                        />
                                        <p className="text-xs text-muted-foreground">
                                            Email tidak dapat diubah melalui halaman ini.
                                        </p>
                                    </div>

                                    <Separator />

                                    <div className="flex justify-end">
                                        <Button type="submit" disabled={isUpdatingProfile}>
                                            {isUpdatingProfile && (
                                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                            )}
                                            Simpan Perubahan
                                        </Button>
                                    </div>
                                </form>
                            </CardContent>
                        </Card>
                    </TabsContent>

                    {/* ── Change Password Tab ── */}
                    <TabsContent value="password" className="mt-4">
                        <Card>
                            <CardHeader>
                                <CardTitle>Ganti Password</CardTitle>
                                <CardDescription>
                                    Pastikan akun Anda menggunakan password yang kuat untuk menjaga keamanan.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <form onSubmit={handlePasswordSubmit} className="space-y-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="current_password">Password Saat Ini</Label>
                                        <PasswordInput
                                            id="current_password"
                                            value={currentPassword}
                                            onChange={(e) => setCurrentPassword(e.target.value)}
                                            placeholder="Masukkan password saat ini"
                                            required
                                            autoComplete="current-password"
                                        />
                                        {errors.current_password && (
                                            <p className="text-sm text-destructive">{errors.current_password}</p>
                                        )}
                                    </div>

                                    <div className="space-y-2">
                                        <Label htmlFor="new_password">Password Baru</Label>
                                        <PasswordInput
                                            id="new_password"
                                            value={newPassword}
                                            onChange={(e) => setNewPassword(e.target.value)}
                                            placeholder="Masukkan password baru"
                                            required
                                            autoComplete="new-password"
                                        />
                                        {errors.password && (
                                            <p className="text-sm text-destructive">{errors.password}</p>
                                        )}
                                    </div>

                                    <div className="space-y-2">
                                        <Label htmlFor="confirm_password">Konfirmasi Password Baru</Label>
                                        <PasswordInput
                                            id="confirm_password"
                                            value={confirmPassword}
                                            onChange={(e) => setConfirmPassword(e.target.value)}
                                            placeholder="Ulangi password baru"
                                            required
                                            autoComplete="new-password"
                                        />
                                    </div>

                                    <Separator />

                                    <div className="flex justify-end">
                                        <Button type="submit" disabled={isUpdatingPassword}>
                                            {isUpdatingPassword && (
                                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                            )}
                                            Perbarui Password
                                        </Button>
                                    </div>
                                </form>
                            </CardContent>
                        </Card>
                    </TabsContent>
                </Tabs>
            </div>
        </FinanceAppLayout>
    );
}
