"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 { Badge } from "@/components/ui/Badge";
import { userService } from "@/services/user.service";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import { formatDate } from "@/utils/helpers";

interface QuickAction {
  label: string;
  route: string;
  variant: 'primary' | 'secondary';
}

interface ProfilePageProps {
  role: 'admin' | 'employee';
  roleLabel: string;
  badgeVariant: 'danger' | 'warning' | 'info' | 'success';
  primaryColor: 'blue' | 'green';
  quickActions: QuickAction[];
}

/**
 * Shared profile page component for admin and employee
 */
export default function ProfilePage({
  role,
  roleLabel,
  badgeVariant,
  primaryColor,
  quickActions,
}: ProfilePageProps) {
  const { user, refreshUser } = useAuth();
  const router = useRouter();
  const [isEditing, setIsEditing] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const colorClasses = {
    blue: {
      primaryBtn: 'bg-blue-600 hover:bg-blue-700',
      secondaryBtn: 'border-blue-600 text-blue-600 hover:bg-blue-600',
    },
    green: {
      primaryBtn: 'bg-green-600 hover:bg-green-700',
      secondaryBtn: 'border-green-600 text-green-600 hover:bg-green-600',
    },
  };

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

  if (!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 colors = colorClasses[primaryColor];

  return (
    <div className="p-6">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-900 mb-6">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-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Informations personnelles</h2>
              </div>
              <div className="p-6">
                {!isEditing ? (
                  <dl className="space-y-4">
                    <div>
                      <dt className="text-sm font-medium text-gray-700">
                        Prénom
                      </dt>
                      <dd className="text-lg text-gray-900">{user.firstName}</dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-700">
                        Nom
                      </dt>
                      <dd className="text-lg text-gray-900">{user.lastName}</dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-700">
                        Email
                      </dt>
                      <dd className="text-lg text-gray-900">{user.email}</dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-700">
                        Téléphone
                      </dt>
                      <dd className="text-lg text-gray-900">
                        {user.phone || "Non renseigné"}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-700">
                        Rôle
                      </dt>
                      <dd className="mt-1">
                        <Badge variant={badgeVariant}>{roleLabel}</Badge>
                      </dd>
                    </div>
                    <div className="pt-4">
                      <button
                        onClick={() => setIsEditing(true)}
                        className={`${colors.primaryBtn} text-white font-bold px-6 py-3 rounded-lg transition-all shadow-md`}
                      >
                        Modifier mes informations
                      </button>
                    </div>
                  </dl>
                ) : (
                  <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={`${colors.primaryBtn} disabled:bg-gray-400 text-white font-bold px-6 py-3 rounded-lg transition-all shadow-md`}
                      >
                        {isSubmitting ? "Enregistrement..." : "Enregistrer"}
                      </button>
                      <button
                        type="button"
                        onClick={handleCancel}
                        disabled={isSubmitting}
                        className="border-2 border-gray-300 hover:bg-gray-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-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Statut du compte</h2>
              </div>
              <div className="p-6 space-y-4">
                <dl>
                  <dt className="text-sm font-medium text-gray-700">
                    Membre depuis
                  </dt>
                  <dd className="text-sm text-gray-900 mt-1">
                    {formatDate(user.createdAt)}
                  </dd>
                </dl>
              </div>
            </div>

            {/* Quick Actions Card */}
            <div className="bg-white rounded-xl shadow-md overflow-hidden border border-gray-200 mt-6">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Actions rapides</h2>
              </div>
              <div className="p-6 space-y-2">
                {quickActions.map((action, index) => (
                  <button
                    key={index}
                    onClick={() => router.push(action.route)}
                    className={`w-full font-bold px-6 py-3 rounded-lg transition-all ${
                      action.variant === 'primary'
                        ? `${colors.primaryBtn} text-white shadow-md`
                        : `border-2 ${colors.secondaryBtn} hover:text-white`
                    }`}
                  >
                    {action.label}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
