"use client";

import Breadcrumbs from "@/components/user/components/Breadcrumbs";
import { useTranslation } from "@/hooks/useTranslation";
import { updateProfile } from "@/libs/axios/modules/user";
import { UserModel } from "@/models";
import { AnimatePresence, motion } from "framer-motion";
import Cookies from "js-cookie";
import { Camera, Images, LogOut } from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useRef, useState } from "react";
import { toast } from "react-toastify";

function initialName(name: string) {
    if (!name) return "?";
    return name.split(" ").slice(0, 2).map((w) => w[0]).join("").toUpperCase();
}

function InputField({
    title,
    value,
    onChange,
    placeholder,
    type = "text",
    error,
}: {
    title: string;
    value: string;
    onChange: (v: string) => void;
    placeholder?: string;
    type?: string;
    error?: string;
}) {
    return (
        <div className="flex flex-col">
            <div className="border-b border-slate-100 pt-4 pb-1">
                <p className="text-xs text-slate-400 capitalize mb-1">{title}</p>
                <input
                    type={type}
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    placeholder={placeholder}
                    className="w-full text-lg font-semibold text-slate-800 placeholder:text-slate-300 outline-none bg-transparent py-1"
                />
            </div>
            {error && <p className="text-xs text-red-500 font-medium mt-1">{error}</p>}
        </div>
    );
}

function PhotoModal({
    open,
    onSelectFile,
    onClose,
}: {
    open: boolean;
    onSelectFile: (file: File) => void;
    onClose: () => void;
}) {
    const fileRef = useRef<HTMLInputElement>(null);
    const cameraRef = useRef<HTMLInputElement>(null);
    const { t } = useTranslation();

    const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) { onSelectFile(file); onClose(); }
    };

    return (
        <AnimatePresence>
            {open && (
                <>
                    <motion.div
                        className="fixed inset-0 z-9999 bg-black/40 backdrop-blur-sm"
                        onClick={onClose}
                        initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                    />
                    <div className="fixed inset-0 z-10000 flex items-end md:items-center justify-center">
                        <motion.div
                            className="bg-white w-full md:max-w-sm md:rounded-3xl rounded-t-3xl overflow-hidden shadow-xl"
                            initial={{ y: "100%" }} animate={{ y: 0 }} exit={{ y: "100%" }}
                            transition={{ type: "spring", stiffness: 300, damping: 30 }}
                        >
                            <div className="px-6 pt-6 pb-2">
                                <p className="font-semibold text-xl text-slate-800 capitalize">{t("select profile photo")}</p>
                                <p className="text-sm text-slate-500 mt-0.5">
                                    {t("choose a photo that makes you smile")}
                                </p>
                            </div>
                            <div className="px-6 py-4 flex flex-col gap-3">
                                <button
                                    onClick={() => cameraRef.current?.click()}
                                    className="flex items-center gap-3 p-5 border border-slate-100 rounded-2xl hover:bg-slate-50 transition-colors cursor-pointer"
                                >
                                    <Camera className="w-5 h-5 text-slate-700" />
                                    <span className="font-medium text-slate-800 capitalize">{t("camera")}</span>
                                </button>
                                <input ref={cameraRef} type="file" accept="image/*" capture="user" className="sr-only" onChange={handleFile} />

                                <button
                                    onClick={() => fileRef.current?.click()}
                                    className="flex items-center gap-3 p-5 border border-slate-100 rounded-2xl hover:bg-slate-50 transition-colors cursor-pointer"
                                >
                                    <Images className="w-5 h-5 text-slate-700" />
                                    <span className="font-medium text-slate-800 capitalize">{t("gallery")}</span>
                                </button>
                                <input ref={fileRef} type="file" accept="image/*" className="sr-only" onChange={handleFile} />
                            </div>
                            <div className="px-6 pb-6">
                                <button
                                    onClick={onClose}
                                    className="w-full py-3 rounded-full bg-slate-100 text-slate-600 font-medium text-sm hover:bg-slate-200 transition-colors cursor-pointer"
                                >
                                    {t("close")}
                                </button>
                            </div>
                        </motion.div>
                    </div>
                </>
            )}
        </AnimatePresence>
    );
}

function LogoutModal({ open, onClose }: { open: boolean; onClose: () => void }) {
    const { t, language } = useTranslation();
    const router = useRouter();

    const handleLogout = () => {
        Cookies.remove("token");
        Cookies.remove("user");
        Cookies.remove("isLoggedIn");
        router.push(`/${language}`);
    };

    return (
        <AnimatePresence>
            {open && (
                <>
                    <motion.div
                        className="fixed inset-0 z-9999 bg-black/40 backdrop-blur-sm"
                        onClick={onClose}
                        initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                    />
                    <div className="fixed inset-0 z-10000 flex items-center justify-center p-4">
                        <motion.div
                            className="bg-white rounded-2xl shadow-xl p-6 w-full max-w-sm flex flex-col gap-4"
                            initial={{ scale: 0.92, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            exit={{ scale: 0.92, opacity: 0 }}
                            transition={{ type: "spring", stiffness: 300, damping: 25 }}
                        >
                            <div className="flex flex-col gap-1">
                                <p className="font-semibold text-slate-800">{t("logout")}</p>
                                <p className="text-sm text-slate-500">{t("are you sure you want to logout?")}</p>
                            </div>
                            <div className="flex gap-2">
                                <button
                                    onClick={onClose}
                                    className="flex-1 py-3 rounded-xl bg-slate-100 text-slate-600 font-medium text-sm hover:bg-slate-200 transition-colors cursor-pointer"
                                >
                                    {t("cancel")}
                                </button>
                                <button
                                    onClick={handleLogout}
                                    className="flex-1 py-3 rounded-xl bg-red-500 text-white font-semibold text-sm hover:bg-red-600 transition-colors cursor-pointer"
                                >
                                    {t("logout")}
                                </button>
                            </div>
                        </motion.div>
                    </div>
                </>
            )}
        </AnimatePresence>
    );
}

interface Props {
    token: string;
    user: UserModel;
}

type FormState = {
    id: string;
    avatar: string;
    name: string;
    email: string;
    phone: string;
    username: string;
    bio: string;
};

type ErrorState = {
    name: string;
    email: string;
    phone: string;
    username: string;
    bio: string;
};

export default function ProfilePage({ token, user: initialUser }: Props) {
    const { t } = useTranslation();
    const router = useRouter();
    const [avatarFile, setAvatarFile] = useState<File | null>(null);

    const [state, setState] = useState<FormState>({
        id: initialUser.id ?? "",
        avatar: initialUser.avatar ?? "",
        name: initialUser.name ?? "",
        email: initialUser.email ?? "",
        phone: initialUser.phone ?? "",
        username: initialUser.username ?? "",
        bio: initialUser.bio ?? "",
    });
    const [errors, setErrors] = useState<ErrorState>({ name: "", email: "", phone: "", username: "", bio: "" });
    const [saving, setSaving] = useState(false);
    const [showPhoto, setShowPhoto] = useState(false);
    const [showLogout, setShowLogout] = useState(false);
    const [avatarPreview, setAvatarPreview] = useState<string>(initialUser.avatar ?? "");

    const set = (key: keyof FormState) => (value: string) =>
        setState((prev) => ({ ...prev, [key]: value }));

    const handlePhotoSelect = useCallback((file: File) => {
        setAvatarPreview(URL.createObjectURL(file));
        setAvatarFile(file);
    }, []);

    const validate = () => {
        const errs: ErrorState = { name: "", email: "", phone: "", username: "", bio: "" };
        if (!state.name) errs.name = "name required";
        if (!state.email) errs.email = "name required";
        else if (!/\S+@\S+\.\S+/.test(state.email)) errs.email = "name required";
        if (!state.phone) errs.phone = "name required";
        else if (!/^\d+$/.test(state.phone)) errs.phone = "name required";
        setErrors(errs);
        return !Object.values(errs).some(Boolean);
    };

    const onSubmit = useCallback(async () => {
        if (!validate() || saving) return;
        setSaving(true);
        try {
            const { data: res } = await updateProfile(token, {
                ...state,
                avatar: avatarFile,
            });
            if (res?.data) {
                toast.success(t("success.updated"));
            }
        } catch (err: any) {
            const message = err?.data?.message ?? err?.message ?? "Terjadi kesalahan";
            if (err?.data?.errors) setErrors(err.data.errors);
            else toast.error(message);
        } finally {
            setSaving(false);
        }
    }, [state, saving, token, t]);

    return (
        <div className="flex flex-col gap-6 w-full">
            <Breadcrumbs
                title="Dashboard"
                subtitle={[
                    { title: "Profil", href: "/user/profile" },
                    { title: t("profile settings"), href: "/user/profile/setting" },
                ]}
                href="/user"
            />

            <div className="sticky top-0 z-10 bg-white border-b border-slate-100 rounded-t-xl shadow-sm">
                <div className="flex items-center justify-between px-4 py-3">
                    <div className="flex items-center gap-2">
                        <button
                            onClick={() => router.back()}
                            className="w-9 h-9 rounded-xl border border-slate-200 flex items-center justify-center hover:bg-slate-50 transition-colors cursor-pointer"
                        >
                            <svg className="w-4 h-4 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                            </svg>
                        </button>
                        <span className="text-base font-semibold text-slate-800 capitalize">{t("profile settings")}</span>
                    </div>
                    <button
                        onClick={onSubmit}
                        disabled={saving}
                        className={`text-sm font-semibold transition-colors cursor-pointer capitalize
                            ${saving ? "text-slate-300" : "text-primary-500 hover:text-primary-600"}`}
                    >
                        {saving ? "Menyimpan..." : t("save")}
                    </button>
                </div>
            </div>

            <div className="bg-white rounded-2xl shadow-sm p-6 flex flex-col gap-6">

                <div className="flex items-center gap-5">
                    <div className="relative shrink-0">
                        {avatarPreview ? (
                            <img src={avatarPreview} alt="avatar" className="w-20 h-20 rounded-full object-cover" />
                        ) : (
                            <div className="w-20 h-20 rounded-full bg-slate-100 flex items-center justify-center">
                                <span className="font-semibold text-lg text-slate-600">{initialName(state.name)}</span>
                            </div>
                        )}
                    </div>
                    <button
                        onClick={() => setShowPhoto(true)}
                        className="flex items-center gap-2 px-4 py-2 border border-slate-300 rounded-full text-sm text-slate-600 hover:bg-slate-50 transition-colors cursor-pointer"
                    >
                        <Camera className="w-4 h-4" />
                        <span className="capitalize">{t("change photo")}</span>
                    </button>
                </div>

                <div className="flex flex-col">
                    <InputField title={t("name")} value={state.name} onChange={set("name")} placeholder={t("name")} error={errors.name} />
                    <InputField title={t("email")} value={state.email} onChange={set("email")} placeholder={t("email")} type="email" error={errors.email} />
                    <InputField title={t("phone")} value={state.phone} onChange={set("phone")} placeholder={t("phone")} type="tel" error={errors.phone} />
                    {initialUser.isWriter && (
                        <>
                            <InputField title={t("username")} value={state.username} onChange={set("username")} placeholder={t("username")} error={errors.username} />
                            <InputField title={t("bio profile")} value={state.bio} onChange={set("bio")} placeholder={t("bio profile")} error={errors.bio} />
                        </>
                    )}
                </div>

                <button
                    onClick={() => setShowLogout(true)}
                    className="w-full flex items-center justify-center gap-2 mt-2 py-4 border border-red-300 rounded-xl text-red-500 font-semibold text-sm hover:bg-red-50 transition-colors cursor-pointer capitalize"
                >
                    <LogOut className="w-4 h-4" />
                    {t("logout")}
                </button>
            </div>

            <PhotoModal open={showPhoto} onSelectFile={handlePhotoSelect} onClose={() => setShowPhoto(false)} />
            <LogoutModal open={showLogout} onClose={() => setShowLogout(false)} />
        </div>
    );
}