import React, { useEffect, useState } from "react";
import { CardContent } from "@/shared/common/ui/card";
import { Badge } from "@/shared/common/ui/badge";
import {
  ChevronLeft,
  Mail,
  CircleUser,
  Phone,
  UserPen,
  RefreshCw,
  CheckCircle2,
  Clock,
  User,
  AlertCircle,
  Save,
  SquareUserRound,
} from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { useNavigate } from "react-router-dom";
import { useAuthUser } from "../../../hooks/useAuthUser";
import { useTranslation } from "react-i18next";
import { motion } from "framer-motion";
import { Input } from "@/shared/common/ui/input";
import { toast } from "sonner";
import { updateProfile } from "@/shared/services/authService";
const UpdateProfile = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { userDetails, isLoading, isError, refetch } = useAuthUser();
  const [error, setError] = useState("");
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [loading, setLoading] = useState(false);
  const [userName, setUserName] = useState(userDetails?.username);
  const [email, setEmail] = useState(userDetails?.email);
  const [englishName, setEnglishName] = useState(userDetails?.name.en);
  const [amharicName, setAmharicName] = useState(userDetails?.name.am);
  const [phoneNumber, setPhoneNumber] = useState(userDetails?.phoneNumber);
  const [success, setSuccess] = useState(false);
  useEffect(() => {
    if (userDetails) {
      setUserName(userDetails.username ?? "");
      setEmail(userDetails.email ?? "");
      setEnglishName(userDetails.name?.en ?? "");
      setAmharicName(userDetails.name?.am ?? "");
      setPhoneNumber(userDetails.phoneNumber ?? "");
    }
  }, [userDetails]);
  // Animation variants
  const container = {
    hidden: { opacity: 0 },
    show: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
        delayChildren: 0.2,
      },
    },
  };

  const item = {
    hidden: { opacity: 0, y: 20 },
    show: { opacity: 1, y: 0, transition: { duration: 0.4 } },
  };
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSuccess(false);
    // check for empty field
    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);
    // Phone number validation: must start with +2519 and followed by 8 digits
    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 updateProfile({
        email,
        username: userName,
        phoneNumber,
        name: {
          am: amharicName,
          en: englishName,
        },
      });
      setSuccess(true);
      toast.success(t("profile.profileUpdateSuccess"), {
        description: t("profile.profileUpdated"),
      });

      //setTimeout(() => (window.location.href = "/profile"), 1200);
    } catch (error: any) {
      const message = error?.message || t("profile.profileUpdateFailed");
      setError(message);
      toast.error(t("profile.profileUpdateFailed"), {
        description: message,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen w-full bg-gradient-to-br from-background via-secondary/20 to-background flex flex-col">
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between p-4 sm:p-6 lg:p-8 border-b border-border/50 backdrop-blur-sm bg-background/80"
      >
        <Button
          onClick={() => navigate(-1)}
          variant="outline"
          className="flex items-center gap-2 px-4 py-2 rounded-lg hover:bg-secondary/50 transition-all duration-200 hover:scale-105 active:scale-95"
        >
          <ChevronLeft className="w-4 h-4 sm:w-5 sm:h-5" />
          <span className="text-sm sm:text-base">Back</span>
        </Button>

        <div className="flex flex-col items-center text-center">
          <h1 className="text-xl sm:text-2xl lg:text-3xl font-bold text-foreground bg-gradient-to-r from-primary-500 to-primary-600 bg-clip-text text-transparent">
            Profile Settings
          </h1>
          <p className="text-xs sm:text-sm text-muted-foreground mt-1 hidden sm:block">
            Manage your account information
          </p>
        </div>

        <div className="w-12 sm:w-14" />
      </motion.div>

      <div className="flex-1 flex items-center justify-center p-4 sm:p-6 lg:p-8">
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          transition={{ duration: 0.5, type: "spring", stiffness: 100 }}
          className="w-full max-w-2xl rounded-2xl overflow-hidden shadow-2xl bg-card border border-border/50 backdrop-blur-sm"
        >
          {/* Profile Header with Green Gradient */}
          <div className="relative bg-gradient-to-r from-primary-500 via-primary-600 to-primary-600 h-32 sm:h-40 lg:h-48 overflow-hidden">
            {/* Decorative Elements */}
            <div className="absolute inset-0 bg-grid-white/10" />
            <div className="absolute top-0 left-0 w-32 h-32 bg-white/10 rounded-full -translate-x-1/2 -translate-y-1/2" />
            <div className="absolute bottom-0 right-0 w-24 h-24 bg-white/10 rounded-full translate-x-1/3 translate-y-1/3" />

            {/* Status Badge */}
            <div className="absolute top-4 right-4">
              <Badge
                className={`rounded-full text-xs px-3 py-1.5 backdrop-blur-sm border-0 ${
                  userDetails?.status === "accepted"
                    ? "bg-primary-500/20 text-primary-100 border border-primary-400/50"
                    : "bg-yellow-500/20 text-yellow-100 border border-yellow-400/50"
                }`}
              >
                {userDetails?.status === "accepted" ? (
                  <div className="flex items-center gap-1">
                    <CheckCircle2 className="w-3 h-3" />
                    <span>Verified</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    <span>Pending</span>
                  </div>
                )}
              </Badge>
            </div>

            {/* Profile Avatar */}
            <div className="absolute -bottom-6 sm:-bottom-8 left-1/2 transform -translate-x-1/2">
              <motion.div
                whileHover={{ scale: 1.08, rotate: 5 }}
                whileTap={{ scale: 0.95 }}
                className="relative h-24 w-24 sm:h-32 sm:w-32 rounded-full border-4 border-card bg-card shadow-2xl overflow-hidden group"
              >
                <div className="absolute inset-0 bg-gradient-to-br from-primary-400/30 to-primary-600/30 flex items-center justify-center group-hover:from-primary-400/40 group-hover:to-primary-600/40 transition-all duration-300">
                  <UserPen className="w-8 h-8 sm:w-12 sm:h-12 text-white drop-shadow-sm" />
                </div>
                <div className="absolute inset-0 border-2 border-white/20 rounded-full" />
                {/* Online Status Indicator */}
                <div className="absolute bottom-1 right-1 sm:bottom-2 sm:right-2 w-3 h-3 sm:w-4 sm:h-4 bg-primary-400 border-2 border-card rounded-full" />
              </motion.div>
            </div>
          </div>

          <CardContent className="pt-16 sm:pt-20 pb-6 sm:pb-8 px-4 sm:px-6 lg:px-8">
            {/* User Info Header */}
            <div className="text-center mb-6 sm:mb-8">
              <motion.h2
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
                className="text-2xl sm:text-3xl lg:text-4xl font-bold text-foreground mb-2"
              >
                Update Your Profile
              </motion.h2>
              <motion.p
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.3 }}
                className="text-muted-foreground text-sm sm:text-base lg:text-lg"
              >
                Keep your information current and accurate
              </motion.p>
            </div>

            {/* Current User Display */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.4 }}
              className="flex flex-col items-center justify-center gap-3 mb-6 sm:mb-8 p-4 bg-primary-50/50 dark:bg-primary-950/20 rounded-xl border border-primary-200/50 dark:border-primary-800/50"
            >
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-gradient-to-r from-primary-500 to-primary-600 flex items-center justify-center">
                  <User className="w-5 h-5 text-white" />
                </div>
                <div className="text-left">
                  <p className="text-lg sm:text-xl font-semibold text-foreground">
                    {userDetails?.name?.en || "Not set"}
                  </p>
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <SquareUserRound className="w-4 h-4" />
                    <span>
                      {userDetails?.employee[0]?.positions[0]?.name?.en || ""}
                    </span>
                  </div>
                </div>
              </div>
            </motion.div>

            {/* Success Message */}
            {success && (
              <motion.div
                initial={{ opacity: 0, y: -10, scale: 0.95 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: -10, scale: 0.95 }}
                className="mb-6 p-4 bg-primary-50 dark:bg-primary-950/30 border border-primary-200 dark:border-primary-800 rounded-xl flex items-center gap-3 backdrop-blur-sm"
              >
                <CheckCircle2 className="w-5 h-5 text-primary-600 dark:text-primary-400 flex-shrink-0" />
                <div>
                  <p className="text-sm font-medium text-primary-800 dark:text-primary-300">
                    Profile updated successfully!
                  </p>
                  <p className="text-xs text-primary-600 dark:text-primary-400/70">
                    Your changes have been saved
                  </p>
                </div>
              </motion.div>
            )}

            {/* Form */}
            <motion.form
              variants={container}
              initial="hidden"
              animate="show"
              className="space-y-4 sm:space-y-6"
              onSubmit={handleSubmit}
            >
              {/* Form Fields Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
                {/* Username */}
                <motion.div variants={item} className="relative md:col-span-2">
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Username
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors duration-200 group-focus-within:text-primary-600">
                      <User className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-focus-within:text-primary-600" />
                    </div>
                    <Input
                      placeholder="Enter your username"
                      className="pl-10 h-11 sm:h-12 bg-input/50 border-border/50 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all duration-200 group-hover:border-primary-500/50"
                      value={userName}
                      onChange={(e) => setUserName(e.target.value)}
                    />
                  </div>
                  {errors.userName && (
                    <p className="text-xs text-destructive mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      {errors.userName}
                    </p>
                  )}
                </motion.div>

                {/* English Name */}
                <motion.div variants={item} className="relative">
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    English Name
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors duration-200 group-focus-within:text-primary-600">
                      <UserPen className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-focus-within:text-primary-600" />
                    </div>
                    <Input
                      placeholder="English name"
                      className="pl-10 h-11 sm:h-12 bg-input/50 border-border/50 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all duration-200 group-hover:border-primary-500/50"
                      value={englishName}
                      onChange={(e) => setEnglishName(e.target.value)}
                    />
                  </div>
                  {errors.englishName && (
                    <p className="text-xs text-destructive mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      {errors.englishName}
                    </p>
                  )}
                </motion.div>

                {/* Amharic Name */}
                <motion.div variants={item} className="relative">
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Amharic Name
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors duration-200 group-focus-within:text-primary-600">
                      <UserPen className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-focus-within:text-primary-600" />
                    </div>
                    <Input
                      placeholder="Amharic name"
                      className="pl-10 h-11 sm:h-12 bg-input/50 border-border/50 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all duration-200 group-hover:border-primary-500/50"
                      value={amharicName}
                      onChange={(e) => setAmharicName(e.target.value)}
                    />
                  </div>
                  {errors.amharicName && (
                    <p className="text-xs text-destructive mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      {errors.amharicName}
                    </p>
                  )}
                </motion.div>

                {/* Email */}
                <motion.div variants={item} className="relative">
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Email Address
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors duration-200 group-focus-within:text-primary-600">
                      <Mail className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-focus-within:text-primary-600" />
                    </div>
                    <Input
                      type="email"
                      placeholder="your@email.com"
                      className="pl-10 h-11 sm:h-12 bg-input/50 border-border/50 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all duration-200 group-hover:border-primary-500/50"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </div>
                  {errors.email && (
                    <p className="text-xs text-destructive mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      {errors.email}
                    </p>
                  )}
                </motion.div>

                {/* Phone Number */}
                <motion.div variants={item} className="relative">
                  <label className="text-sm font-medium text-foreground mb-2 block">
                    Phone Number
                  </label>
                  <div className="relative group">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors duration-200 group-focus-within:text-primary-600">
                      <Phone className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-focus-within:text-primary-600" />
                    </div>
                    <Input
                      type="tel"
                      placeholder="+1 (555) 000-0000"
                      className="pl-10 h-11 sm:h-12 bg-input/50 border-border/50 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all duration-200 group-hover:border-primary-500/50"
                      value={phoneNumber}
                      onChange={(e) => setPhoneNumber(e.target.value)}
                    />
                  </div>
                  {errors.phoneNumber && (
                    <p className="text-xs text-destructive mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      {errors.phoneNumber}
                    </p>
                  )}
                </motion.div>
              </div>

              {/* Submit Button */}
              <motion.div variants={item} className="pt-4 sm:pt-6">
                <Button
                  type="submit"
                  className="w-full h-11 sm:h-12 bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 text-white font-semibold text-sm sm:text-base shadow-lg rounded-xl transition-all duration-200 hover:shadow-xl hover:scale-[1.02] active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
                  disabled={loading}
                >
                  {loading ? (
                    <span className="flex items-center justify-center gap-2">
                      <RefreshCw className="animate-spin h-4 w-4 sm:h-5 sm:w-5" />
                      <span>Updating Profile...</span>
                    </span>
                  ) : (
                    <span className="flex items-center justify-center gap-2">
                      <Save className="h-4 w-4 sm:h-5 sm:w-5" />
                      <span>Update Profile</span>
                    </span>
                  )}
                </Button>
              </motion.div>
            </motion.form>
          </CardContent>
        </motion.div>
      </div>
    </div>
  );
};

export default UpdateProfile;
