"use client";

import { User as UserIcon, Mail, Phone, MapPin, Calendar, Shield, Building, Hash, Clock, Edit } from "lucide-react";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { User } from "@/types/auth";

interface UserProfileModalProps {
  user: User | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onEdit?: (user: User) => void;
}

const UserTypeBadge = ({ userType }: { userType: string }) => {
  const typeLabels: Record<string, string> = {
    client: "Client",
    super_admin: "Administrateur",
    ca_member: "Membre CA",
    manager: "Manager",
    account_manager: "Gestionnaire",
    cashier: "Caissier",
    it_staff: "Personnel IT",
    other_staff: "Autres Personnel",
    agency_agent: "Agent d'agence",
    community_leader: "Chef de communauté",
  };

  const typeColors: Record<string, string> = {
    client: "bg-blue-500",
    super_admin: "bg-red-500",
    ca_member: "bg-purple-500",
    manager: "bg-indigo-500",
    account_manager: "bg-green-500",
    cashier: "bg-orange-500",
    it_staff: "bg-cyan-500",
    other_staff: "bg-gray-500",
    agency_agent: "bg-yellow-500",
    community_leader: "bg-pink-500",
  };

  return (
    <Badge className={cn("text-white", typeColors[userType] ?? "bg-gray-500")}>
      {typeLabels[userType] ?? userType}
    </Badge>
  );
};

const StatusBadge = ({ user }: { user: User }) => {
  if (user.is_active && user.is_verified) {
    return (
      <Badge variant="default" className="bg-green-500">
        Actif et vérifié
      </Badge>
    );
  }
  if (user.is_active && !user.is_verified) {
    return (
      <Badge variant="secondary" className="bg-orange-500">
        Actif non vérifié
      </Badge>
    );
  }
  if (!user.is_active) {
    return (
      <Badge variant="destructive" className="bg-red-500">
        Inactif
      </Badge>
    );
  }
  return (
    <Badge variant="secondary" className="bg-gray-500">
      Statut inconnu
    </Badge>
  );
};

const getInitials = (name: string) => {
  return name
    .split(" ")
    .map((word) => word[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString("fr-FR", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

export function UserProfileModal({ user, open, onOpenChange, onEdit }: UserProfileModalProps) {
  if (!user) return null;

  const fullName = `${user.first_name} ${user.last_name}`.trim();
  const displayName = fullName || user.email;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <DialogTitle className="flex items-center gap-3">
              <UserIcon className="h-5 w-5" />
              Profil utilisateur
            </DialogTitle>
            {onEdit && (
              <Button variant="outline" size="sm" onClick={() => onEdit(user)} className="flex items-center gap-2">
                <Edit className="h-4 w-4" />
                Modifier
              </Button>
            )}
          </div>
          <DialogDescription>Informations détaillées sur l&apos;utilisateur</DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Section Avatar et informations principales */}
          <div className="flex items-start gap-4">
            <Avatar className="h-20 w-20">
              <AvatarImage src={user.profile?.avatar ?? undefined} alt={displayName} />
              <AvatarFallback className="text-lg">{getInitials(displayName)}</AvatarFallback>
            </Avatar>

            <div className="flex-1 space-y-2">
              <div>
                <h3 className="text-xl font-semibold">{displayName}</h3>
                <p className="text-muted-foreground">{user.email}</p>
              </div>

              <div className="flex flex-wrap gap-2">
                <UserTypeBadge userType={user.user_type} />
                <StatusBadge user={user} />
                {user.is_staff && (
                  <Badge variant="outline" className="border-blue-500 text-blue-500">
                    <Shield className="mr-1 h-3 w-3" />
                    Staff
                  </Badge>
                )}
                {user.is_superuser && (
                  <Badge variant="outline" className="border-red-500 text-red-500">
                    <Shield className="mr-1 h-3 w-3" />
                    Super Admin
                  </Badge>
                )}
              </div>
            </div>
          </div>

          <Separator />

          {/* Informations de contact */}
          <div className="space-y-4">
            <h4 className="text-lg font-medium">Informations de contact</h4>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="flex items-center gap-2">
                <Mail className="text-muted-foreground h-4 w-4" />
                <span className="text-sm font-medium">Email:</span>
                <span className="text-sm">{user.email}</span>
              </div>

              {user.phone_number && (
                <div className="flex items-center gap-2">
                  <Phone className="text-muted-foreground h-4 w-4" />
                  <span className="text-sm font-medium">Téléphone:</span>
                  <span className="text-sm">{user.phone_number}</span>
                </div>
              )}

              {user.profile?.address && (
                <div className="flex items-center gap-2">
                  <MapPin className="text-muted-foreground h-4 w-4" />
                  <span className="text-sm font-medium">Adresse:</span>
                  <span className="text-sm">{user.profile.address}</span>
                </div>
              )}

              {user.profile?.city && (
                <div className="flex items-center gap-2">
                  <MapPin className="text-muted-foreground h-4 w-4" />
                  <span className="text-sm font-medium">Ville:</span>
                  <span className="text-sm">{user.profile.city}</span>
                </div>
              )}
            </div>
          </div>

          <Separator />

          {/* Informations professionnelles */}
          {(user.employee_id ?? user.department) && (
            <>
              <div className="space-y-4">
                <h4 className="text-lg font-medium">Informations professionnelles</h4>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  {user.employee_id && (
                    <div className="flex items-center gap-2">
                      <Hash className="text-muted-foreground h-4 w-4" />
                      <span className="text-sm font-medium">ID Employé:</span>
                      <span className="text-sm">{user.employee_id}</span>
                    </div>
                  )}

                  {user.department && (
                    <div className="flex items-center gap-2">
                      <Building className="text-muted-foreground h-4 w-4" />
                      <span className="text-sm font-medium">Département:</span>
                      <span className="text-sm">{user.department}</span>
                    </div>
                  )}
                </div>
              </div>
              <Separator />
            </>
          )}

          {/* Informations système */}
          <div className="space-y-4">
            <h4 className="text-lg font-medium">Informations système</h4>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="flex items-center gap-2">
                <Calendar className="text-muted-foreground h-4 w-4" />
                <span className="text-sm font-medium">Inscription:</span>
                <span className="text-sm">{formatDate(user.date_joined)}</span>
              </div>

              {user.last_login && (
                <div className="flex items-center gap-2">
                  <Clock className="text-muted-foreground h-4 w-4" />
                  <span className="text-sm font-medium">Dernière connexion:</span>
                  <span className="text-sm">{formatDate(user.last_login)}</span>
                </div>
              )}

              <div className="flex items-center gap-2">
                <Shield className="text-muted-foreground h-4 w-4" />
                <span className="text-sm font-medium">Vérifié:</span>
                <span className="text-sm">{user.is_verified ? "✅ Oui" : "❌ Non"}</span>
              </div>

              <div className="flex items-center gap-2">
                <Shield className="text-muted-foreground h-4 w-4" />
                <span className="text-sm font-medium">2FA:</span>
                <span className="text-sm">{user.has_two_factor ? "✅ Activé" : "❌ Désactivé"}</span>
              </div>
            </div>
          </div>

          {/* Biographie si disponible */}
          {user.profile?.bio && (
            <>
              <Separator />
              <div className="space-y-4">
                <h4 className="text-lg font-medium">Biographie</h4>
                <p className="text-muted-foreground text-sm">{user.profile.bio}</p>
              </div>
            </>
          )}
        </div>

        <div className="flex justify-end pt-4">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Fermer
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
