"use client";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAuth } from "@/contexts/AuthContext";
import { profileUpdateSchema, ProfileUpdateFormData } from "@/lib/validations";
import { Input } from "@/components/ui/Input";
import Button from "@/components/Button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import { userService } from "@/services/user.service";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import { ROUTES } from "@/utils/constants";
import { formatDate } from "@/utils/helpers";
import { Modal } from "@/components/ui/Modal";

export const dynamic = 'force-dynamic';

export default function ProfilePage() {
  const { user, isAuthenticated, refreshUser, logout } = useAuth();
  const router = useRouter();
  const [isEditing, setIsEditing] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isReady, setIsReady] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ProfileUpdateFormData>({
    resolver: zodResolver(profileUpdateSchema),
    defaultValues: {
      firstName: user?.firstName || "",
      lastName: user?.lastName || "",
      phone: user?.phone || "",
    },
  });

  useEffect(() => {
    if (!isAuthenticated || !user) {
      router.push(ROUTES.LOGIN);
    } else {
      setIsReady(true);
    }
  }, [isAuthenticated, user, router]);

  if (!isReady || !user) {
    return null;
  }

  const onSubmit = async (data: ProfileUpdateFormData) => {
    setIsSubmitting(true);
    try {
      await userService.updateProfile(data);
      await refreshUser();
      toast.success("Profil mis à jour avec succès");
      setIsEditing(false);
    } catch (error: any) {
      toast.error(error.message || "Erreur lors de la mise à jour du profil");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCancel = () => {
    reset({
      firstName: user?.firstName || "",
      lastName: user?.lastName || "",
      phone: user?.phone || "",
    });
    setIsEditing(false);
  };

  const handleDeleteAccount = async () => {
    setIsDeleting(true);
    try {
      await userService.archiveAccount();
      toast.success("Votre compte a été supprimé avec succès");
      logout();
      router.push(ROUTES.HOME);
    } catch (error: any) {
      toast.error(error.message || "Erreur lors de la suppression du compte");
    } finally {
      setIsDeleting(false);
      setShowDeleteModal(false);
    }
  };

  const getRoleBadgeVariant = (role: string) => {
    switch (role) {
      case "admin":
        return "danger";
      case "employee":
        return "warning";
      default:
        return "info";
    }
  };

  const getRoleLabel = (role: string) => {
    switch (role) {
      case "admin":
        return "Administrateur";
      case "employee":
        return "Employé";
      default:
        return "Client";
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-beige-100 via-beige-50 to-beige-100 py-8">
      <div className="container mx-auto px-4 max-w-4xl">
        <h1 className="text-4xl font-bold text-gray-800 mb-8">Mon profil</h1>

        <div className="grid md:grid-cols-3 gap-6">
          {/* Profile Info Card */}
          <div className="md:col-span-2">
            <div className="bg-white rounded-xl shadow-md overflow-hidden border border-beige-300">
              <div className="px-6 py-4 border-b border-beige-300">
                <h2 className="text-xl font-bold text-gray-800">Informations personnelles</h2>
              </div>
              <div className="p-6">
                {!isEditing ? (
                  <div className="space-y-4">
                    <div>
                      <span className="text-sm font-medium text-gray-700 block">
                        Prénom
                      </span>
                      <p className="text-lg text-gray-800">{user.firstName}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-700 block">
                        Nom
                      </span>
                      <p className="text-lg text-gray-800">{user.lastName}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-700 block">
                        Email
                      </span>
                      <p className="text-lg text-gray-800">{user.email}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-700 block">
                        Téléphone
                      </span>
                      <p className="text-lg text-gray-800">
                        {user.phone || "Non renseigné"}
                      </p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-700 block">
                        Rôle
                      </span>
                      <div className="mt-1">
                        <Badge variant={getRoleBadgeVariant(user.role)}>
                          {getRoleLabel(user.role)}
                        </Badge>
                      </div>
                    </div>
                    <div className="pt-4 flex flex-wrap gap-3">
                      <button
                        onClick={() => setIsEditing(true)}
                        className="bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 text-white font-bold px-6 py-3 rounded-lg transition-all shadow-lg hover:scale-105 duration-300"
                      >
                        Modifier mes informations
                      </button>
                      <button
                        onClick={() => setShowDeleteModal(true)}
                        className="bg-red-600 hover:bg-red-700 text-white font-bold px-6 py-3 rounded-lg transition-all shadow-lg hover:scale-105 duration-300"
                      >
                        Supprimer mon compte
                      </button>
                    </div>
                  </div>
                ) : (
                  <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                    <Input
                      id="firstName"
                      type="text"
                      label="Prénom"
                      error={errors.firstName?.message}
                      {...register("firstName")}
                      required
                    />
                    <Input
                      id="lastName"
                      type="text"
                      label="Nom"
                      error={errors.lastName?.message}
                      {...register("lastName")}
                      required
                    />
                    <Input
                      id="email"
                      type="email"
                      label="Email"
                      value={user.email}
                      disabled
                      helperText="L'email ne peut pas être modifié"
                    />
                    <Input
                      id="phone"
                      type="tel"
                      label="Téléphone"
                      error={errors.phone?.message}
                      {...register("phone")}
                    />
                    <div className="flex gap-3">
                      <button
                        type="submit"
                        disabled={isSubmitting}
                        className="bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 disabled:bg-gray-400 text-white font-bold px-6 py-3 rounded-lg transition-all shadow-lg hover:scale-105 duration-300"
                      >
                        {isSubmitting ? "Enregistrement..." : "Enregistrer"}
                      </button>
                      <button
                        type="button"
                        onClick={handleCancel}
                        disabled={isSubmitting}
                        className="border-2 border-beige-300 hover:bg-beige-100 text-gray-700 font-bold px-6 py-3 rounded-lg transition-all"
                      >
                        Annuler
                      </button>
                    </div>
                  </form>
                )}
              </div>
            </div>
        </div>

        {/* Account Status Card */}
        <div>
          <div className="bg-white rounded-xl shadow-md overflow-hidden border border-beige-300">
            <div className="px-6 py-4 border-b border-beige-300">
              <h2 className="text-xl font-bold text-gray-800">Statut du compte</h2>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <span className="text-sm font-medium text-gray-700 block">
                  Membre depuis
                </span>
                <p className="text-sm text-gray-800 mt-1">
                  {formatDate(user.createdAt)}
                </p>
              </div>
            </div>
          </div>

          {/* Quick Actions Card */}
          <div className="bg-white rounded-xl shadow-md overflow-hidden border border-beige-300 mt-6">
            <div className="px-6 py-4 border-b border-beige-300">
              <h2 className="text-xl font-bold text-gray-800">Actions rapides</h2>
            </div>
            <div className="p-6 space-y-2">
              {user.role === "CLIENT" && (
                <>
                  <button
                    onClick={() => router.push(ROUTES.GAME)}
                    className="w-full bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 text-white font-bold px-6 py-3 rounded-lg transition-all shadow-lg hover:scale-105 duration-300"
                  >
                    Jouer
                  </button>
                  <button
                    onClick={() => router.push(ROUTES.HISTORY)}
                    className="w-full border-2 border-primary-500 text-primary-500 hover:bg-primary-500 hover:text-white font-bold px-6 py-3 rounded-lg transition-all"
                  >
                    Historique
                  </button>
                </>
              )}
              {user.role === "EMPLOYEE" && (
                <button
                  onClick={() => router.push(ROUTES.EMPLOYEE_DASHBOARD)}
                  className="w-full border-2 border-primary-500 text-primary-500 hover:bg-primary-500 hover:text-white font-bold px-6 py-3 rounded-lg transition-all"
                >
                  Tableau de bord
                </button>
              )}
              {user.role === "ADMIN" && (
                <button
                  onClick={() => router.push(ROUTES.ADMIN_DASHBOARD)}
                  className="w-full border-2 border-primary-500 text-primary-500 hover:bg-primary-500 hover:text-white font-bold px-6 py-3 rounded-lg transition-all"
                >
                  Administration
                </button>
              )}
            </div>
          </div>

        </div>
      </div>
      </div>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="Confirmer la suppression"
      >
        <div className="flex items-center justify-center w-12 h-12 mx-auto mb-4 bg-red-100 rounded-full">
          <svg className="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
        </div>
        <h3 className="text-lg font-semibold text-center text-gray-900 mb-2">
          Êtes-vous sûr de vouloir supprimer votre compte ?
        </h3>
        <p className="text-sm text-center text-gray-600 mb-6">
          Votre compte sera supprimé et vous ne pourrez plus vous connecter. Vos données seront conservées et un administrateur pourra réactiver votre compte si nécessaire.
        </p>
        <div className="flex gap-3">
          <button
            onClick={() => setShowDeleteModal(false)}
            disabled={isDeleting}
            className="flex-1 border-2 border-gray-300 hover:bg-gray-100 text-gray-700 font-bold px-6 py-3 rounded-lg transition-all"
          >
            Annuler
          </button>
          <button
            onClick={handleDeleteAccount}
            disabled={isDeleting}
            className="flex-1 bg-red-600 hover:bg-red-700 disabled:bg-red-300 text-white font-bold px-6 py-3 rounded-lg transition-all"
          >
            {isDeleting ? "Suppression..." : "Supprimer"}
          </button>
        </div>
      </Modal>
    </div>
  );
}
