"use client";

import React, { useState, useEffect } from "react";
import { QRCodeCanvas } from "qrcode.react";
import { BASE_URL } from "@/Constant";
import Image from "next/image";

/* -------------------- TYPES -------------------- */

interface Standard {
  standardNumber?: string;
  standard?: string;
  glaApprovalStatus?: string;
  typeScheme?: string;
}

interface UserData {
  _id?: string;
  organisationName?: string;
  uniqueID?: string;
  userEmail?: string;
  logo?: string;
  isVerified?: boolean;
  about?: string;
  qualification?: string;
  coreSkills?: string;
  speciliedArea?: string;
  workExperience?: string;
  keyAchivements?: string;
  achivedTrainingCertificates?: string;
  standards?: (string | Standard[])[];
  Iagree?: boolean;
  Ido?: boolean;
  updatedAt?: string;
}

interface UserDigitalCardProps {
  userData?: UserData;
}

/* -------------------- COMPONENT -------------------- */

const UserDigitalCard: React.FC<UserDigitalCardProps> = ({ userData }) => {
  const [currentUrl, setCurrentUrl] = useState<string>("");
  const [accreditation, setAccreditation] = useState<UserData>({});
  const [standards, setStandards] = useState<Standard[]>([]);

  /* -------------------- EFFECT -------------------- */

  useEffect(() => {
    if (!userData) return;

    setAccreditation(userData);

    // Parse standards safely
    if (userData.standards && userData.standards.length > 0) {
      try {
        const first = userData.standards[0];

        if (typeof first === "string") {
          const parsed = JSON.parse(first);
          setStandards(Array.isArray(parsed) ? parsed : []);
        } else {
          setStandards(Array.isArray(first) ? first : []);
        }
      } catch (err) {
        console.error("Standards parse error:", err);
        setStandards([]);
      }
    }

    if (typeof window !== "undefined") {
      setCurrentUrl(window.location.href);
    }
  }, [userData]);

  /* -------------------- HELPERS -------------------- */

  const getLogoUrl = (logoPath?: string): string | null => {
    if (!logoPath) return null;

    let path = String(logoPath).replace(/\\/g, "/");
    if (path.startsWith("/")) path = path.slice(1);

    return `${BASE_URL}${path}`.replace(/([^:]\/)\/+/g, "$1");
  };

  /* -------------------- EMPTY STATE -------------------- */

  if (!userData) {
    return (
      <div className="mx-auto max-w-4xl bg-white rounded-2xl shadow-xl p-8 text-center">
        <p className="text-gray-500">No user data available</p>
      </div>
    );
  }

  /* -------------------- JSX -------------------- */

  return (
    <div className="mx-auto w-full max-w-4xl bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
      {/* HEADER */}
      <div className="bg-gradient-to-r from-blue-600 to-indigo-700 p-6 text-white">
        <div className="flex flex-col md:flex-row justify-between gap-6">
          <div className="flex gap-6">
            {/* LOGO */}
            <div className="w-28 h-28 bg-white rounded-full p-2">
              {accreditation.logo ? (
                <Image
                  src={getLogoUrl(accreditation.logo) || ""}
                  alt="Logo"
                  width={100}
                  height={100}
                  className="rounded-full object-cover"
                  unoptimized
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center rounded-full bg-blue-100 text-blue-700 text-2xl font-bold">
                  {(accreditation.organisationName || "U")[0]}
                </div>
              )}
            </div>

            {/* INFO */}
            <div>
              <h1 className="text-2xl font-bold">
                {accreditation.organisationName || "Personal Profile"}
              </h1>

              <p className="text-sm text-blue-200">
                ID: {accreditation.uniqueID || "N/A"}
              </p>

              <p className="text-sm">{accreditation.userEmail || "N/A"}</p>

              <span className="inline-block mt-2 px-3 py-1 rounded-full bg-white/20 text-sm">
                {accreditation.isVerified ? "Verified ✅" : "Not Verified"}
              </span>
            </div>
          </div>

          {/* QR */}
          {currentUrl && (
            <div className="bg-white p-2 rounded">
              <QRCodeCanvas value={currentUrl} size={90} />
            </div>
          )}
        </div>
      </div>

      {/* BODY */}
      <div className="p-6">
        <h2 className="text-xl font-bold mb-2">About</h2>
        <p className="text-gray-700">
          {accreditation.about || "No information provided"}
        </p>

        {/* STANDARDS */}
        {standards.length > 0 && (
          <>
            <h2 className="text-xl font-bold mt-6 mb-2">
              Standards & Certifications
            </h2>

            <div className="grid md:grid-cols-2 gap-4">
              {standards.map((s, i) => (
                <div key={i} className="p-3 bg-purple-50 rounded">
                  <h3 className="font-semibold">
                    {s.standardNumber || `Standard ${i + 1}`}
                  </h3>
                  <p className="text-sm">{s.standard}</p>
                </div>
              ))}
            </div>
          </>
        )}

        {/* FOOTER INFO */}
        <div className="mt-6 border-t pt-4 flex justify-between text-sm text-gray-500">
          <span>ID: {accreditation._id?.slice(0, 8)}</span>
          <span>
            Updated:{" "}
            {accreditation.updatedAt
              ? new Date(accreditation.updatedAt).toLocaleDateString("en-IN")
              : "N/A"}
          </span>
        </div>
      </div>
    </div>
  );
};

export default UserDigitalCard;
