"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";
import DateObject from "react-date-object";
import gregorian from "react-date-object/calendars/gregorian";
import gregorian_en from "react-date-object/locales/gregorian_en";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import { AppShell } from "@/components/app/AppShell";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { ApiError, apiGet } from "@/lib/api";
import { mediaUrl } from "@/lib/media";

interface RoleAssignment {
  role_name: string;
  role_label: string;
  branch_name?: string | null;
}

interface StaffProfile {
  id: number;
  name?: string;
  first_name?: string | null;
  last_name?: string | null;
  email?: string | null;
  mobile?: string | null;
  national_code?: string | null;
  personnel_code?: string | null;
  employment_type_label?: string | null;
  gender?: string | null;
  birth_date?: string | null;
  avatar_path?: string | null;
  is_active?: boolean;
  role_assignments?: RoleAssignment[];
  role_labels?: string[];
}

function formatJalali(gregorianDate?: string | null) {
  if (!gregorianDate) return "—";
  const normalized = gregorianDate.slice(0, 10);
  const date = new DateObject({
    date: normalized,
    format: "YYYY-MM-DD",
    calendar: gregorian,
    locale: gregorian_en,
  }).convert(persian, persian_fa);
  return date.format("YYYY/MM/DD");
}

function genderLabel(gender?: string | null) {
  if (gender === "male") return "آقا";
  if (gender === "female") return "خانم";
  return "—";
}

function uniqueRoles(assignments?: RoleAssignment[]) {
  const seen = new Set<string>();
  const items: Array<{ name: string; label: string }> = [];
  for (const item of assignments ?? []) {
    if (!item.role_name || seen.has(item.role_name)) continue;
    seen.add(item.role_name);
    items.push({ name: item.role_name, label: item.role_label });
  }
  return items;
}

function InfoRow({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="grid grid-cols-[8rem_1fr] items-start gap-3 border-b border-[var(--border)] py-3 last:border-b-0 sm:grid-cols-[10rem_1fr]">
      <dt className="text-sm text-[var(--muted)]">{label}</dt>
      <dd className="text-sm font-medium">{children}</dd>
    </div>
  );
}

export default function StaffProfilePage() {
  const { id } = useParams<{ id: string }>();
  const [user, setUser] = useState<StaffProfile | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      setLoading(true);
      setError(null);
      try {
        setUser(await apiGet<StaffProfile>(`/users/${id}`));
      } catch (err) {
        setError(err instanceof ApiError ? err.message : "خطا در بارگذاری پروفایل");
      } finally {
        setLoading(false);
      }
    })();
  }, [id]);

  const displayName = user
    ? [user.first_name, user.last_name].filter(Boolean).join(" ") || user.name || "کارمند"
    : "";
  const avatarSrc = mediaUrl(user?.avatar_path);
  const roles = uniqueRoles(user?.role_assignments);
  const initials = displayName
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0])
    .join("");

  return (
    <AppShell
      title="مشاهده کارمند"
      subtitle={displayName || `شناسه #${id}`}
      showBack
      breadcrumbLabels={{ staff: displayName || undefined }}
    >
      {error ? <Alert tone="error">{error}</Alert> : null}

      {loading ? (
        <PageContentSkeleton rows={5} />
      ) : user ? (
        <div className="space-y-4">
          <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-6">
            <div className="mb-6 flex flex-wrap items-center gap-4">
              {avatarSrc ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={avatarSrc}
                  alt={displayName}
                  className="h-20 w-20 rounded-full object-cover"
                />
              ) : (
                <div className="flex h-20 w-20 items-center justify-center rounded-full bg-slate-200 text-lg font-bold text-slate-700">
                  {initials || "؟"}
                </div>
              )}
              <div>
                <h2 className="text-lg font-bold">{displayName}</h2>
                <p className="mt-1 text-sm text-[var(--muted)]">
                  {user.is_active ? "فعال" : "غیرفعال"}
                  {user.personnel_code ? ` · کد پرسنلی ${user.personnel_code}` : ""}
                </p>
              </div>
            </div>

            <dl>
              <InfoRow label="نام">{user.first_name || "—"}</InfoRow>
              <InfoRow label="نام خانوادگی">{user.last_name || "—"}</InfoRow>
              <InfoRow label="کد ملی">{user.national_code || "—"}</InfoRow>
              <InfoRow label="موبایل">{user.mobile || "—"}</InfoRow>
              <InfoRow label="ایمیل">{user.email || "—"}</InfoRow>
              <InfoRow label="کد پرسنلی">{user.personnel_code || "—"}</InfoRow>
              <InfoRow label="نوع همکاری">{user.employment_type_label || "—"}</InfoRow>
              <InfoRow label="جنسیت">{genderLabel(user.gender)}</InfoRow>
              <InfoRow label="تاریخ تولد">{formatJalali(user.birth_date)}</InfoRow>
              <InfoRow label="وضعیت">{user.is_active ? "فعال" : "غیرفعال"}</InfoRow>
              <InfoRow label="نقش‌ها">
                {roles.length > 0 ? (
                  <span className="flex flex-wrap gap-2">
                    {roles.map((role) => (
                      <Link
                        key={role.name}
                        href={`/staff?role=${encodeURIComponent(role.name)}`}
                        className="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-primary hover:bg-slate-200"
                      >
                        {role.label}
                      </Link>
                    ))}
                  </span>
                ) : (
                  "—"
                )}
              </InfoRow>
            </dl>
          </div>

          <div className="flex flex-wrap gap-2">
            <Link href={`/staff/${id}/edit`}>
              <Button>ویرایش</Button>
            </Link>
            <Link href={`/staff/${id}/roles`}>
              <Button variant="secondary">نقش‌ها</Button>
            </Link>
            <Link href={`/staff/${id}/reset-password`}>
              <Button variant="secondary">بازنشانی رمز</Button>
            </Link>
            <Link href="/staff">
              <Button variant="secondary">بازگشت به فهرست</Button>
            </Link>
          </div>
        </div>
      ) : null}
    </AppShell>
  );
}
