"use client";

import { Edit3, RotateCcw } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useProfile } from "./profile-api";
import { ProfileContactDialog } from "./profile-contact-dialog";
import { ProfileEditDialog } from "./profile-edit-dialog";
import { ProfilePasswordDialog } from "./profile-password-dialog";
import type { Profile } from "./profile-types";

type ProfileDialog = "edit" | "email" | "mobile" | "password" | null;

export function ProfilePageView() {
  const t = useTranslations("dashboard.profile");
  const { profile, error, isLoading, refetch } = useProfile();
  const [activeDialog, setActiveDialog] = useState<ProfileDialog>(null);

  if (isLoading) return <ProfileLoading label={t("status.loading")} />;
  if (error || !profile) return <ProfileError message={error instanceof Error ? error.message : t("status.loadError")} retryLabel={t("actions.retry")} onRetry={() => void refetch()} />;

  return (
    <div className="w-full">
      <BasicInformationCard profile={profile} t={t} openDialog={setActiveDialog} />
      <ProfileEditDialog profile={profile} open={activeDialog === "edit"} onOpenChange={(open) => setActiveDialog(open ? "edit" : null)} />
      <ProfileContactDialog kind="email" open={activeDialog === "email"} onOpenChange={(open) => setActiveDialog(open ? "email" : null)} />
      <ProfileContactDialog kind="mobile" open={activeDialog === "mobile"} onOpenChange={(open) => setActiveDialog(open ? "mobile" : null)} />
      <ProfilePasswordDialog open={activeDialog === "password"} onOpenChange={(open) => setActiveDialog(open ? "password" : null)} />
    </div>
  );
}

function BasicInformationCard({ profile, t, openDialog }: { profile: Profile; t: ReturnType<typeof useTranslations>; openDialog: (dialog: ProfileDialog) => void }) {
  const avatarUrl = profile.avatar_url ?? profile.avatar ?? "/images/avatars/default.png";

  return (
    <section className="rounded-2xl border border-border bg-card">
      <header className="flex items-center justify-between border-b px-6 py-4">
        <h2 className="font-bold">{t("sections.basic")}</h2>
        <Button variant="outline" size="icon" className="rounded-xl" aria-label={t("actions.edit")} onClick={() => openDialog("edit")}><Edit3 /></Button>
      </header>
      <div className="px-6 pb-7 pt-6">
        <Avatar className="mx-auto size-[120px] border border-border"><AvatarImage src={avatarUrl} /><AvatarFallback>{profile.first_name?.[0] ?? "U"}</AvatarFallback></Avatar>
        <div className="mt-12 grid gap-x-28 gap-y-7 sm:grid-cols-2">
          <ProfileColumn>
            <ProfileField label={t("fields.firstName")} value={profile.first_name} />
            <ProfileField label={t("fields.username")} value={profile.username} />
            <ProfileField label={t("fields.language")} value={profileLanguage(profile.language, t)} />
            <ProfileField label={t("fields.birthDate")} value={profile.birth_date} />
            <ProfileField label={t("fields.email")} value={profile.email} actionLabel={t("actions.change")} onAction={() => openDialog("email")} />
            <ProfileField label={t("fields.linkedin")} value={profile.linkedin_url} />
          </ProfileColumn>
          <ProfileColumn>
            <ProfileField label={t("fields.lastName")} value={profile.last_name} />
            <ProfileField label={t("fields.role")} value={profileRoleName(profile.role)} />
            <ProfileField label={t("fields.gender")} value={profileGender(profile.gender, t)} />
            <ProfileField label={t("fields.mobile")} value={profileMobile(profile)} valueDirection="ltr" actionLabel={t("actions.change")} onAction={() => openDialog("mobile")} />
            <ProfileField label={t("fields.password")} actionLabel={t("actions.changePassword")} onAction={() => openDialog("password")} />
            <ProfileField label={t("fields.x")} value={profile.x_url} />
          </ProfileColumn>
        </div>
      </div>
    </section>
  );
}

function ProfileColumn({ children }: { children: React.ReactNode }) {
  return <dl className="space-y-7">{children}</dl>;
}

interface ProfileFieldProps {
  label: string;
  value?: string | null;
  valueDirection?: "ltr" | "rtl";
  actionLabel?: string;
  onAction?: () => void;
}

function ProfileField({ label, value, valueDirection, actionLabel, onAction }: ProfileFieldProps) {
  if (!value && !actionLabel) return null;
  return (
    <div className="space-y-1.5">
      <dt className="text-sm text-muted-foreground">{label}</dt>
      <dd className="flex min-h-6 items-center gap-2 font-semibold">
        {value ? <span dir={valueDirection} className="min-w-0 break-words">{value}</span> : null}
        {actionLabel ? <button type="button" className="inline-flex items-center gap-1 text-sm font-semibold text-primary underline-offset-4 hover:underline" onClick={onAction}><Edit3 className="size-4" />{actionLabel}</button> : null}
      </dd>
    </div>
  );
}

function profileRoleName(role: Profile["role"]) {
  return typeof role === "string" ? role : role?.name;
}

function profileLanguage(language: Profile["language"], t: ReturnType<typeof useTranslations>) {
  if (language === "ar") return `${t("values.arabic")} 🇸🇦`;
  if (language === "en") return t("values.english");
  return language;
}

function profileGender(gender: Profile["gender"], t: ReturnType<typeof useTranslations>) {
  if (gender === "male") return t("values.male");
  if (gender === "female") return t("values.female");
  return gender;
}

function profileMobile(profile: Profile) {
  if (!profile.mobile_number) return undefined;
  if (profile.mobile_number.startsWith("+")) return profile.mobile_number;
  return `${profile.mobile_country_code ?? ""}${profile.mobile_number}`;
}

function ProfileLoading({ label }: { label: string }) {
  return <div role="status" aria-label={label} className="h-[560px] animate-pulse rounded-2xl border bg-card"><div className="h-16 border-b" /><div className="mx-auto mt-8 size-28 rounded-full bg-muted" /></div>;
}

function ProfileError({ message, retryLabel, onRetry }: { message: string; retryLabel: string; onRetry: () => void }) {
  return <div className="flex min-h-72 flex-col items-center justify-center gap-4 rounded-2xl border bg-card p-6 text-center"><p className="text-muted-foreground">{message}</p><Button onClick={onRetry}><RotateCcw />{retryLabel}</Button></div>;
}
