import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Head, router, useForm } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { AlertCircle, Eye, EyeOff, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import MasukCardLayout from './masuk-card-layout';

type LoginForm = {
    nip: string;
    password: string;
    remember: boolean;
};

interface LoginProps {
    flash?: {
        step?: number;
        message?: string;
        tahuns?: { id: number; nama: string; jenis: string }[];
    };
}

export default function IndexMasuk({ flash }: LoginProps) {
    const [step, setStep] = useState(1);
    const [showPassword, setShowPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [selectedYear, setSelectedYear] = useState<string | null>(null);
    const [yearError, setYearError] = useState<string | null>(null);
    const [errorMessage, setErrorMessage] = useState<string | null>(null);
    const [openErrorDialog, setOpenErrorDialog] = useState(false);

    const isLocal = import.meta.env.MODE === 'development';

    const { data, setData, post, processing } = useForm<LoginForm>({
        nip: isLocal ? '11223344' : '',
        password: isLocal ? 'password' : '',
        remember: false,
    });

    const container = {
        hidden: { opacity: 0, y: 20 },
        show: {
            opacity: 1,
            y: 0,
            transition: { staggerChildren: 0.15 },
        },
    };

    const item = {
        hidden: { opacity: 0, y: 15 },
        show: { opacity: 1, y: 0 },
    };

    useEffect(() => {
        if (flash?.step === 2) {
            setStep(2);
        }
    }, [flash]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);

        post('/masuk-proses', {
            onFinish: () => setLoading(false),
            onError: (errs: any) => {
                const msg = errs.nip || errs.password || 'Login gagal';
                setErrorMessage(msg);
                setOpenErrorDialog(true); // 🔥 tampilkan dialog error
            },
            onSuccess: (page: any) => {
                if (page.props.flash?.step === 2) {
                    setStep(2);
                }
            },
        });
    };

    const handleTahun = (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedYear) {
            setYearError('Tahun wajib dipilih');
            return;
        }
        router.post('/select-year', { tahun_id: selectedYear });
    };

    return (
        <MasukCardLayout>
            <Head title="Login" />

            {step === 1 && (
                <motion.div key="step1">
                    <motion.form
                        id="user-form-step-1"
                        onSubmit={handleSubmit}
                        className="mx-auto mb-5 flex max-w-md flex-col rounded-md bg-white/80 p-5 shadow-2xl backdrop-blur-md"
                        variants={container}
                        initial="hidden"
                        animate="show"
                    >
                        <motion.div className="grid gap-6">
                            <motion.div variants={item} className="grid gap-2">
                                <Label
                                    htmlFor="nip"
                                    className="text-xs text-black"
                                >
                                    Nomor Induk Pegawai
                                </Label>
                                <Input
                                    id="nip"
                                    name="nip"
                                    type="text"
                                    required
                                    autoFocus
                                    autoComplete="off"
                                    placeholder="Nomor induk pegawai"
                                    className="border-gray-300 text-black"
                                    value={data.nip}
                                    onChange={(e) =>
                                        setData(
                                            'nip',
                                            e.target.value.replace(
                                                /[^0-9]/g,
                                                '',
                                            ),
                                        )
                                    }
                                />
                            </motion.div>

                            <motion.div variants={item} className="grid gap-2">
                                <Label
                                    htmlFor="password"
                                    className="text-xs text-black"
                                >
                                    Kata Sandi
                                </Label>
                                <div className="relative">
                                    <Input
                                        id="password"
                                        name="password"
                                        type={
                                            showPassword ? 'text' : 'password'
                                        }
                                        required
                                        autoComplete="off"
                                        placeholder="#########"
                                        className="border-gray-300 text-black"
                                        value={data.password}
                                        onChange={(e) =>
                                            setData('password', e.target.value)
                                        }
                                    />
                                    <button
                                        type="button"
                                        onClick={() =>
                                            setShowPassword(!showPassword)
                                        }
                                        className="absolute inset-y-0 right-3 flex items-center text-gray-500 hover:text-gray-700"
                                    >
                                        {showPassword ? (
                                            <EyeOff className="h-5 w-5" />
                                        ) : (
                                            <Eye className="h-5 w-5" />
                                        )}
                                    </button>
                                </div>
                            </motion.div>
                        </motion.div>
                    </motion.form>

                    <motion.div
                        variants={item}
                        initial="hidden"
                        animate="show"
                        transition={{ delay: 0.5 }}
                        className="w-full"
                    >
                        <Button
                            form="user-form-step-1"
                            type="submit"
                            disabled={loading}
                            className="w-full bg-emerald-700 text-white hover:bg-emerald-800"
                        >
                            {loading ? (
                                <>
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                    Loading...
                                </>
                            ) : (
                                'Silahkan Login'
                            )}
                        </Button>
                    </motion.div>
                </motion.div>
            )}

            {step === 2 && (
                <motion.div key="step2">
                    <motion.form
                        id="user-form-step-2"
                        onSubmit={handleTahun}
                        className="mx-auto mb-5 flex max-w-md flex-col rounded-md bg-white/80 p-5 shadow-2xl backdrop-blur-md"
                    >
                        <div className="grid gap-6">
                            <div className="grid gap-2 text-black">
                                <Label htmlFor="tahun" className="text-xs">
                                    Pilih Tahun
                                </Label>
                                <Select
                                    onValueChange={(value) => {
                                        setSelectedYear(value);
                                        setYearError(null);
                                    }}
                                >
                                    <SelectTrigger
                                        id="tahun"
                                        className="w-full"
                                    >
                                        <SelectValue placeholder="Pilih Tahun" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {flash?.tahuns?.map((t) => (
                                            <SelectItem
                                                key={t.id}
                                                value={t.id.toString()}
                                            >
                                                {t.nama} - {t.jenis}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError message={yearError || ''} />
                            </div>
                        </div>
                    </motion.form>

                    <motion.div
                        variants={item}
                        initial="hidden"
                        animate="show"
                        transition={{ delay: 0.5 }}
                        className="w-full"
                    >
                        <Button
                            form="user-form-step-2"
                            type="submit"
                            className="w-full bg-emerald-700 text-white hover:bg-emerald-600"
                            disabled={processing}
                        >
                            {processing && (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            )}
                            Masuk Dashboard
                        </Button>
                    </motion.div>
                </motion.div>
            )}

            <Dialog open={openErrorDialog} onOpenChange={setOpenErrorDialog}>
                <DialogContent className="w-[320px] rounded-2xl border-0 bg-gradient-to-br from-white to-gray-50 p-6 shadow-2xl backdrop-blur-md">
                    <motion.div
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ duration: 0.25 }}
                    >
                        <DialogHeader className="text-center">
                            <div className="flex justify-center">
                                <div className="rounded-full bg-red-100 p-3">
                                    <AlertCircle className="h-8 w-8 text-red-600" />
                                </div>
                            </div>
                            <DialogTitle className="text-center text-lg font-semibold text-gray-900">
                                Gagal Login
                            </DialogTitle>
                            <DialogDescription className="text-center text-gray-600">
                                {errorMessage}
                            </DialogDescription>
                        </DialogHeader>

                        <DialogFooter className="flex justify-center">
                            {/* <Button
                                onClick={() => setOpenErrorDialog(false)}
                                className="rounded-full bg-red-600 px-6 text-white hover:bg-red-700"
                            >
                                Tutup
                            </Button> */}
                        </DialogFooter>
                    </motion.div>
                </DialogContent>
            </Dialog>
        </MasukCardLayout>
    );
}
