"use client";
import { useState } 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";

export default function ProfilePage() {
  const { user, isAuthenticated, refreshUser } = useAuth();
  const router = useRouter();
  const [isEditing, setIsEditing] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  if (!isAuthenticated || !user) {
    router.push(ROUTES.LOGIN);
    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 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="py-8 max-w-4xl mx-auto">
      <h1 className="text-3xl font-bold text-gray-900 mb-8">Mon profil</h1>

      <div className="grid md:grid-cols-3 gap-6">
        {/* Profile Info Card */}
        <div className="md:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle>Informations personnelles</CardTitle>
            </CardHeader>
            <CardContent>
              {!isEditing ? (
                <div className="space-y-4">
                  <div>
                    <label className="text-sm font-medium text-gray-500">
                      Prénom
                    </label>
                    <p className="text-lg text-gray-900">{user.firstName}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">
                      Nom
                    </label>
                    <p className="text-lg text-gray-900">{user.lastName}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">
                      Email
                    </label>
                    <p className="text-lg text-gray-900">{user.email}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">
                      Téléphone
                    </label>
                    <p className="text-lg text-gray-900">
                      {user.phone || "Non renseigné"}
                    </p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">
                      Rôle
                    </label>
                    <div className="mt-1">
                      <Badge variant={getRoleBadgeVariant(user.role)}>
                        {getRoleLabel(user.role)}
                      </Badge>
                    </div>
                  </div>
                  <div className="pt-4">
                    <Button onClick={() => setIsEditing(true)}>
                      Modifier mes informations
                    </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"
                      isLoading={isSubmitting}
                      disabled={isSubmitting}
                    >
                      Enregistrer
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleCancel}
                      disabled={isSubmitting}
                    >
                      Annuler
                    </Button>
                  </div>
                </form>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Account Status Card */}
        <div>
          <Card>
            <CardHeader>
              <CardTitle>Statut du compte</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-500">
                  Email vérifié
                </label>
                <div className="mt-1">
                  {user.isEmailVerified ? (
                    <Badge variant="success">Vérifié ✓</Badge>
                  ) : (
                    <Badge variant="warning">Non vérifié</Badge>
                  )}
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">
                  Membre depuis
                </label>
                <p className="text-sm text-gray-900 mt-1">
                  {formatDate(user.createdAt)}
                </p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">
                  Dernière modification
                </label>
                <p className="text-sm text-gray-900 mt-1">
                  {formatDate(user.updatedAt)}
                </p>
              </div>
            </CardContent>
          </Card>

          {/* Quick Actions Card */}
          <Card className="mt-6">
            <CardHeader>
              <CardTitle>Actions rapides</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {user.role === "client" && (
                <>
                  <Button
                    variant="outline"
                    fullWidth
                    onClick={() => router.push(ROUTES.GAME)}
                  >
                    Jouer
                  </Button>
                  <Button
                    variant="outline"
                    fullWidth
                    onClick={() => router.push(ROUTES.HISTORY)}
                  >
                    Historique
                  </Button>
                </>
              )}
              {user.role === "employee" && (
                <Button
                  variant="outline"
                  fullWidth
                  onClick={() => router.push(ROUTES.EMPLOYEE_DASHBOARD)}
                >
                  Tableau de bord
                </Button>
              )}
              {user.role === "admin" && (
                <Button
                  variant="outline"
                  fullWidth
                  onClick={() => router.push(ROUTES.ADMIN_DASHBOARD)}
                >
                  Administration
                </Button>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
