"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import profileImg from '../../../../../../public/assets/profile/profileImage.png';
import ProfileDashboard from "@/components/dashboard/profile/profile-dashboard";

interface UserProfile {
  id: string;
  name: string;
  email: string;
  mobile: string;
  role: string;
  status: string;
  createdAt: string;
  registration: {
    registrationType: string;
    companyName: string | null;
    designation: string | null;
    division: string | null;
    district: string | null;
    upazila: string | null;
  } | null;
}

/* ---------- Small reusable pieces ---------- */

function InfoRow({
  label,
  value,
  icon,
}: {
  label: string;
  value: string | null | undefined;
  icon: string;
}) {
  return (
    <div className="flex items-start gap-3 rounded-lg border border-slate-100 bg-slate-50/60 p-4 transition hover:border-indigo-200 hover:bg-indigo-50/40">
      <span className="mt-0.5 text-lg">{icon}</span>
      <div className="min-w-0">
        <p className="text-xs font-medium uppercase tracking-wide text-slate-400">
          {label}
        </p>
        <h5 className="mt-0.5 truncate text-sm font-semibold text-slate-800 capitalize">
          {value || "N/A"}
        </h5>
      </div>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const isActive = status?.toLowerCase() === "active";
  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ${
        isActive
          ? "bg-emerald-100 text-emerald-700"
          : "bg-amber-100 text-amber-700"
      }`}
    >
      <span
        className={`h-1.5 w-1.5 rounded-full ${
          isActive ? "bg-emerald-500" : "bg-amber-500"
        }`}
      />
      {status}
    </span>
  );
}

/* ---------- Main component ---------- */

export default function UserProfile() {
  const router = useRouter();

  const [user, setUser] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchProfile() {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL?.replace(/\/+$/, "");

        if (!apiUrl) {
          throw new Error("API URL is not configured");
        }

        const url = `${apiUrl}/api/v1/auth/profile`;

        let response = await fetch(url, {
          method: "GET",
          credentials: "include",
          cache: "no-store",
          signal: controller.signal,
        });

        // Access token expired
        if (response.status === 401) {
          const refreshResponse = await fetch(
            `${apiUrl}/api/v1/auth/refresh`,
            {
              method: "POST",
              credentials: "include",
              cache: "no-store",
              signal: controller.signal,
            }
          );

          if (!refreshResponse.ok) {
            router.replace("/signin");
            return;
          }

          response = await fetch(url, {
            method: "GET",
            credentials: "include",
            cache: "no-store",
            signal: controller.signal,
          });
        }

        if (response.status === 401) {
          router.replace("/signin");
          return;
        }

        if (!response.ok) {
          throw new Error("Failed to fetch user profile");
        }

        const result = await response.json();
        setUser(result.data);
      } catch (err) {
        if (controller.signal.aborted) return;
        setError(
          err instanceof Error ? err.message : "Something went wrong"
        );
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchProfile();
    return () => controller.abort();
  }, [router]);

  /* ---------- Loading skeleton ---------- */

  if (loading) {
    return (
      <div className="mx-auto max-w-5xl animate-pulse p-6">
        <div className="mb-6 h-40 rounded-2xl bg-slate-200" />
        <div className="grid gap-4 md:grid-cols-2">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-16 rounded-lg bg-slate-100" />
          ))}
        </div>
      </div>
    );
  }

  /* ---------- Error ---------- */

  if (error) {
    return (
      <div className="mx-auto mt-12 max-w-md rounded-xl border border-red-200 bg-red-50 p-6 text-center">
        <p className="text-2xl">⚠️</p>
        <p className="mt-2 font-semibold text-red-700">{error}</p>
        <button
          onClick={() => window.location.reload()}
          className="mt-4 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-red-700"
        >
          Try again
        </button>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="mx-auto mt-12 max-w-md rounded-xl border border-slate-200 bg-slate-50 p-8 text-center">
        <p className="text-3xl">👤</p>
        <p className="mt-3 font-semibold text-slate-700">No user found.</p>
      </div>
    );
  }

  /* ---------- Initials & meta ---------- */

  const initials = user.name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();

  const joinedDate = new Date(user.createdAt).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  return (
    <div className="bg-gray-50 rounded-2xl p-4 sm:p-6">
      <ProfileDashboard></ProfileDashboard>
    </div>
  );
}