import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { motion } from "framer-motion";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import { CardContent } from "@/shared/common/ui/card";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Badge } from "@/shared/common/ui/badge";
import {
  ChevronLeft,
  CircleUser,
  Mail,
  Phone,
  UserPen,
  RefreshCw,
  Save,
} from "lucide-react";
import { useUsersByID } from "@/super-admin/hooks/useUsers";
import { updateUserProfile } from "@/user-management/services/api/employeePositionsService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

const UpdateProfile = () => {
  const { id } = useParams<{ id: string }>();

  const navigate = useNavigate();
  const { t } = useTranslation();

  const { data: userData, refetch, isLoading } = useUsersByID(id!);
  const [userName, setUserName] = useState("");
  const [email, setEmail] = useState("");
  const [englishName, setEnglishName] = useState("");
  const [amharicName, setAmharicName] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [error, setError] = useState("");
  const { handleError } = useErrorHandler(t);
  // Populate form fields when user data is fetched
  useEffect(() => {
    if (userData) {
      const user = userData;
      setUserName(user.username ?? "");
      setEmail(user.email ?? "");
      setEnglishName(user.name?.en ?? "");
      setAmharicName(user.name?.am ?? "");
      setPhoneNumber(user.phoneNumber ?? "");
    }
  }, [userData]);

  const container = {
    hidden: { opacity: 0 },
    show: { opacity: 1, transition: { staggerChildren: 0.1 } },
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const newErrors: { [key: string]: string } = {};

    if (!email.trim()) newErrors.email = t("profile.emailRequired");
    if (!userName.trim()) newErrors.userName = t("profile.usernameRequired");
    if (!phoneNumber.trim()) newErrors.phoneNumber = t("profile.phoneRequired");
    if (!englishName.trim())
      newErrors.englishName = t("profile.englishNameRequired");
    if (!amharicName.trim())
      newErrors.amharicName = t("profile.amharicNameRequired");

    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) return;

    // Phone number validation
    const phoneRegex = /^(\+2519\d{8}|09\d{8})$/;
    if (!phoneRegex.test(phoneNumber)) {
      setError(t("profile.invalidPhoneFormat"));
      toast.error(t("profile.invalidPhoneFormat"), {
        description: t("profile.validPhoneFormat"),
      });
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setError(t("profile.invalidEmailFormat"));
      toast.error(t("profile.invalidEmailFormat"), {
        description: t("profile.validEmailFormat"),
      });
      return;
    }

    setLoading(true);
    try {
      await updateUserProfile(
        {
          username: userName,
          email,
          phoneNumber,
          name: { en: englishName, am: amharicName },
        },
        id as string,
      );

      toast.success(t("profile.profileUpdateSuccess"), {
        description: t("profile.profileUpdated"),
      });

      refetch(); // refresh data after update
    } catch (err: any) {
      const message = err?.message || t("profile.profileUpdateFailed");
      setError(message);
      handleError(message);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading) return <div>Loading...</div>;

  const user = userData;
  if (!user) return <div>User not found</div>;
  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 to-primary-100/40 dark:from-gray-900 dark:to-gray-800">
      <div className="container mx-auto px-4 py-6">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-6">
          <Button
            onClick={() => navigate(-1)}
            variant="ghost"
            className="flex items-center gap-2 text-primary hover:text-primary-700 hover:bg-primary-300/20 dark:text-primary-300 dark:hover:text-primary-300 px-4 py-2 rounded-full transition-colors">
            <ChevronLeft className="w-5 h-5" />
            <span className="font-medium">{t("common.back")}</span>
          </Button>
        </motion.div>

        {/* Profile Content */}
        <div className="flex justify-center">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.3 }}
            className="w-full max-w-2xl bg-white dark:bg-gray-800 rounded-2xl shadow-xl overflow-hidden border border-gray-100 dark:border-gray-700">
            {/* Profile Header */}
            <div className="relative bg-gradient-to-r from-primary to-primary-300 dark:from-primary-700 dark:to-primary-300 h-32">
              <div className="absolute -bottom-12 left-1/2 transform -translate-x-1/2">
                <motion.div
                  whileHover={{ scale: 1.05 }}
                  className="relative h-24 w-24 rounded-full border-4 border-white dark:border-gray-800 bg-white dark:bg-gray-800 shadow-lg">
                  <div className="absolute inset-0 bg-gradient-to-br from-primary-300 to-primary dark:from-primary-300 dark:to-primary-700 rounded-full flex items-center justify-center">
                    <CircleUser className="w-12 h-12 text-white" />
                  </div>
                </motion.div>
              </div>
            </div>

            {/* Profile Info */}
            <div className="pt-14 pb-6 px-6 text-center">
              <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-100">
                {user.name.en || "___"}
              </h2>
              <p className="text-gray-600 dark:text-gray-400 text-sm mt-1">
                {t("profile.updateProfile")}
              </p>

              <div className="mt-3">
                <Badge
                  variant="outline"
                  className={`rounded-full px-3 py-1 text-xs font-medium ${
                    user.status === "accepted"
                      ? "bg-primary-300/20 text-primary border-primary/30"
                      : "bg-gray-100 text-gray-600 border-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600"
                  }`}>
                  {t(`statusBar.${user.status || "___"}`)}
                </Badge>
              </div>
            </div>

            {/* Update Form */}
            <div className="px-6 pb-8">
              <motion.form
                variants={container}
                initial="hidden"
                animate="show"
                className="space-y-4"
                onSubmit={handleSubmit}>
                {/* Username */}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300 pl-1">
                    {t("profile.username")}
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <UserPen className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                    </div>
                    <Input
                      className="pl-9 rounded-lg border-gray-300 dark:border-gray-600 focus:border-primary focus:ring-primary dark:bg-gray-700 dark:text-gray-100"
                      value={userName}
                      onChange={(e) => setUserName(e.target.value)}
                    />
                  </div>
                  {errors.userName && (
                    <p className="text-sm text-red-600 dark:text-red-400 pl-1">
                      {errors.userName}
                    </p>
                  )}
                </div>

                {/* English Name */}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300 pl-1">
                    {t("profile.englishName")}
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <UserPen className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                    </div>
                    <Input
                      className="pl-9 rounded-lg border-gray-300 dark:border-gray-600 focus:border-primary focus:ring-primary dark:bg-gray-700 dark:text-gray-100"
                      value={englishName}
                      onChange={(e) => setEnglishName(e.target.value)}
                    />
                  </div>
                  {errors.englishName && (
                    <p className="text-sm text-red-600 dark:text-red-400 pl-1">
                      {errors.englishName}
                    </p>
                  )}
                </div>

                {/* Amharic Name */}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300 pl-1">
                    {t("profile.amharicName")}
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <UserPen className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                    </div>
                    <Input
                      className="pl-9 rounded-lg border-gray-300 dark:border-gray-600 focus:border-primary focus:ring-primary dark:bg-gray-700 dark:text-gray-100"
                      value={amharicName}
                      onChange={(e) => setAmharicName(e.target.value)}
                    />
                  </div>
                  {errors.amharicName && (
                    <p className="text-sm text-red-600 dark:text-red-400 pl-1">
                      {errors.amharicName}
                    </p>
                  )}
                </div>

                {/* Email */}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300 pl-1">
                    {t("profile.emailmsg")}
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Mail className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                    </div>
                    <Input
                      type="email"
                      className="pl-9 rounded-lg border-gray-300 dark:border-gray-600 focus:border-primary focus:ring-primary dark:bg-gray-700 dark:text-gray-100"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </div>
                  {errors.email && (
                    <p className="text-sm text-red-600 dark:text-red-400 pl-1">
                      {errors.email}
                    </p>
                  )}
                </div>

                {/* Phone Number */}
                <div className="space-y-1">
                  <label className="text-sm font-medium text-gray-700 dark:text-gray-300 pl-1">
                    {t("profile.phoneNumber")}
                  </label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Phone className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                    </div>
                    <Input
                      type="tel"
                      className="pl-9 rounded-lg border-gray-300 dark:border-gray-600 focus:border-primary focus:ring-primary dark:bg-gray-700 dark:text-gray-100"
                      value={phoneNumber}
                      onChange={(e) => setPhoneNumber(e.target.value)}
                    />
                  </div>
                  {errors.phoneNumber && (
                    <p className="text-sm text-red-600 dark:text-red-400 pl-1">
                      {errors.phoneNumber}
                    </p>
                  )}
                </div>

                {/* Submit Button */}
                <motion.div
                  whileHover={{ scale: 1.01 }}
                  whileTap={{ scale: 0.99 }}
                  className="pt-4">
                  <Button
                    type="submit"
                    className="w-full h-12 bg-gradient-to-r from-primary to-primary-300 hover:from-primary-700 hover:to-primary-300 text-white font-medium rounded-lg shadow-md transition-all duration-200"
                    disabled={loading}>
                    {loading ? (
                      <span className="flex items-center justify-center">
                        <RefreshCw className="animate-spin h-5 w-5 mr-2" />
                        {t("profile.updating")}...
                      </span>
                    ) : (
                      <span className="flex items-center justify-center">
                        <Save className="w-4 h-4 mr-2" />
                        {t("profile.updateProfile")}
                      </span>
                    )}
                  </Button>
                </motion.div>
              </motion.form>
            </div>
          </motion.div>
        </div>
      </div>
    </div>
  );
};

export default UpdateProfile;
