import { StatMetric } from "@/components/shared/stat-metric";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { User } from "@/lib/api/types";
import { cn } from "@/lib/utils";
import {
  Clock3,
  Flag,
  Globe2,
  KeyRound,
  Languages,
  type LucideIcon,
  Mail,
  MapPin,
  Phone,
  ShieldCheck,
  Users2,
} from "lucide-react";

interface UserDetailsLabels {
  accountInfo: string;
  access: string;
  status: string;
  active: string;
  inactive: string;
  email: string;
  phone: string;
  city: string;
  nationality: string;
  gender: string;
  preferredLanguage: string;
  createdAt: string;
  updatedAt: string;
  rolesCount: string;
  permissionsCount: string;
  joinedOn: string;
  roles: string;
  permissions: string;
  noRoles: string;
  noPermissions: string;
  notAvailable: string;
  languageArabic: string;
  languageEnglish: string;
}

interface UserDetailsViewProps {
  locale: string;
  labels: UserDetailsLabels;
  permissions?: Array<{
    key: string;
    label: string;
  }>;
  user: User;
}

interface DetailFieldProps {
  forceLtr?: boolean;
  icon: LucideIcon;
  label: string;
  value: string;
}

function getInitials(name: string) {
  return name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join("");
}

function getStatusBadgeClasses(isActive: boolean) {
  return isActive
    ? "border-emerald-200/80 bg-emerald-500/10 text-emerald-700 dark:border-emerald-900/60 dark:text-emerald-300"
    : "border-slate-200/80 bg-slate-500/10 text-slate-700 dark:border-slate-800 dark:text-slate-300";
}

function DetailField({
  forceLtr = false,
  icon: Icon,
  label,
  value,
}: DetailFieldProps) {
  return (
    <div className="rounded-2xl border border-border/60 bg-background-neutral-50/80 p-4">
      <div className="mb-3 flex items-center gap-2 text-sm font-medium text-muted-foreground">
        <Icon className="h-4 w-4 text-primary" />
        <span>{label}</span>
      </div>
      <p
        dir={forceLtr ? "ltr" : undefined}
        className={cn(
          "break-words text-sm font-semibold text-foreground",
          forceLtr && "text-left",
        )}
      >
        {value}
      </p>
    </div>
  );
}

function getLanguageLabel(
  language: User["preferred_language"],
  labels: UserDetailsLabels,
) {
  if (language === "ar") {
    return labels.languageArabic;
  }

  if (language === "en") {
    return labels.languageEnglish;
  }

  return labels.notAvailable;
}

function getDisplayValue(
  value: string | null | undefined,
  fallback: string,
) {
  if (!value || !value.trim()) {
    return fallback;
  }

  return value;
}

export function UserDetailsView({
  locale,
  labels,
  permissions = [],
  user,
}: UserDetailsViewProps) {
  const roles = user.roles || [];
  const isActive = Boolean(user.is_active);
  const statusLabel = isActive ? labels.active : labels.inactive;
  const joinedOn = user.created_at;
  const updatedOn = user.updated_at;
  const phone = getDisplayValue(user.phone, labels.notAvailable);
  const city = getDisplayValue(user.city, labels.notAvailable);
  const nationality = getDisplayValue(user.nationality, labels.notAvailable);
  const gender = getDisplayValue(user.gender, labels.notAvailable);
  const preferredLanguage = getLanguageLabel(user.preferred_language, labels);

  return (
    <div className="space-y-6">
      <Card className="overflow-hidden">
        <CardContent className="p-0">
          <div className="border-b border-border/60 bg-background-neutral-50/70 px-6 py-6">
            <div className="flex flex-col gap-6 xl:flex-row xl:items-center xl:justify-between">
              <div className="flex flex-col gap-5 sm:flex-row sm:items-center">
                <Avatar className="h-24 w-24 rounded-3xl border border-border/60 ring-4 ring-background">
                  <AvatarImage src={user.avatar || undefined} alt={user.name} />
                  <AvatarFallback className="bg-primary/10 text-xl font-semibold text-primary">
                    {getInitials(user.name)}
                  </AvatarFallback>
                </Avatar>

                <div className="space-y-4">
                  <div className="flex flex-wrap items-center gap-3">
                    <h2 className="text-2xl font-semibold tracking-tight text-foreground">
                      {user.name}
                    </h2>
                    <Badge
                      variant="outline"
                      className={cn(
                        "rounded-full px-3 py-1 text-xs font-semibold",
                        getStatusBadgeClasses(isActive),
                      )}
                    >
                      {statusLabel}
                    </Badge>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {roles.length > 0 ? (
                      roles.map((role) => (
                        <Badge
                          key={role.id}
                          variant="secondary"
                          className="rounded-full px-3 py-1"
                        >
                          {role.label?.trim() || role.name}
                        </Badge>
                      ))
                    ) : (
                      <Badge
                        variant="outline"
                        className="rounded-full px-3 py-1 text-muted-foreground"
                      >
                        {labels.noRoles}
                      </Badge>
                    )}
                  </div>

                  <div className="flex flex-col gap-2 text-sm text-muted-foreground">
                    <div className="flex flex-wrap gap-x-5 gap-y-2">
                      <span className="inline-flex items-center gap-2">
                        <Mail className="h-4 w-4 text-primary" />
                        <span dir="ltr" className="text-left">
                          {user.email}
                        </span>
                      </span>
                      <span className="inline-flex items-center gap-2">
                        <Phone className="h-4 w-4 text-primary" />
                        <span dir="ltr" className="text-left">
                          {phone}
                        </span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid gap-3 sm:grid-cols-2 xl:min-w-[420px]">
                <StatMetric label={labels.status} value={statusLabel} />
                <StatMetric label={labels.rolesCount} value={roles.length} />
                <StatMetric
                  label={labels.permissionsCount}
                  value={permissions.length}
                />
                <StatMetric label={labels.joinedOn} value={joinedOn} />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
        <Card className="overflow-hidden">
          <CardHeader className="border-b">
            <CardTitle className="text-base font-semibold text-foreground text-start">
              {labels.accountInfo}
            </CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 p-6 sm:grid-cols-2">
            <DetailField
              forceLtr
              icon={Mail}
              label={labels.email}
              value={user.email}
            />
            <DetailField
              forceLtr
              icon={Phone}
              label={labels.phone}
              value={phone}
            />
            <DetailField icon={MapPin} label={labels.city} value={city} />
            <DetailField
              icon={Flag}
              label={labels.nationality}
              value={nationality}
            />
            <DetailField icon={Users2} label={labels.gender} value={gender} />
            <DetailField
              icon={Languages}
              label={labels.preferredLanguage}
              value={preferredLanguage}
            />
            <DetailField
              icon={Clock3}
              label={labels.createdAt}
              value={joinedOn}
            />
            <DetailField
              icon={Globe2}
              label={labels.updatedAt}
              value={updatedOn}
            />
          </CardContent>
        </Card>

        <Card className="overflow-hidden">
          <CardHeader className="border-b">
            <CardTitle className="text-base font-semibold text-foreground text-start">
              {labels.access}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-5 p-6">
            <div className="rounded-2xl border border-border/60 bg-background-neutral-50/80 p-4">
              <div className="mb-3 flex items-center gap-2 text-sm font-medium text-muted-foreground">
                <ShieldCheck className="h-4 w-4 text-primary" />
                <span>{labels.roles}</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {roles.length > 0 ? (
                  roles.map((role) => (
                    <Badge
                      key={role.id}
                      variant="secondary"
                      className="rounded-full px-3 py-1"
                    >
                      {role.label?.trim() || role.name}
                    </Badge>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">
                    {labels.noRoles}
                  </p>
                )}
              </div>
            </div>

            <div className="rounded-2xl border border-border/60 bg-background-neutral-50/80 p-4">
              <div className="mb-3 flex items-center gap-2 text-sm font-medium text-muted-foreground">
                <KeyRound className="h-4 w-4 text-primary" />
                <span>{labels.permissions}</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {permissions.length > 0 ? (
                  permissions.map((permission) => (
                    <Badge
                      key={permission.key}
                      variant="outline"
                      className="rounded-full bg-background px-3 py-1 font-mono text-[11px]"
                    >
                      {permission.label}
                    </Badge>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">
                    {labels.noPermissions}
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
