"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import {
  FiArrowLeft, FiMail, FiPhone, FiGlobe, FiMapPin, FiFileText, FiAward,
  FiHash, FiCalendar, FiUsers, FiDownload, FiFolder, FiPlay,
} from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../../(dashboard)/modules/commonstyle/dattabale.module.css";

interface CompanyDoc {
  originalName: string;
  fileName: string;
  filePath: string;
}

interface Company {
  id: number;
  name: string;
  email?: string;
  mobile?: string;
  telephone?: string;
  fax?: string;
  address?: string;
  city?: string;
  country?: { name: string };
  company_code?: string;
  trade_license_no?: string;
  reference_number?: string;
  validity?: string;
  client_group?: string;
  certification_body?: string;
  scope_of_work?: string;
  standards?: any[];
  documents?: CompanyDoc[];
}

const PREMIUM_CSS = `
@keyframes cpFadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.cp-rise { opacity: 0; animation: cpFadeUp 0.5s cubic-bezier(0.22,1,0.36,1) forwards; }
.cp-card { transition: transform 0.18s ease, box-shadow 0.18s ease; }
.cp-card:hover { transform: translateY(-2px); box-shadow: 0 4px 4px rgba(15,23,42,0.03), 0 14px 30px -14px rgba(15,23,42,0.22); }
.cp-scope-row { transition: background 0.15s ease; }
.cp-scope-row:hover { background: #f8fafc; }
`;

// Two earlier attempts guessed specific Unicode code points (\u2261, then a
// handful of symbol ranges) and both failed to actually split the string -
// meaning neither guess matched the real separator character. Rather than
// guess a third specific code point, this matches by Unicode's own general
// category instead: \p{Sm} (Math Symbol, covers characters like \u2261) and
// \p{So} (Other Symbol, covers things like \u2630 and \u27A4) together catch
// essentially the whole family of symbol/bullet-style characters, whatever
// the exact one in this data turns out to be.
function parseScopeItems(text?: string): string[] {
  if (!text) return [];
  return text
    .split(/[\p{Sm}\p{So}]+/gu)
    .map((s) => s.trim())
    .filter(Boolean);
}

function Card({ title, icon, delay, children }: { title: string; icon: React.ReactNode; delay: number; children: React.ReactNode }) {
  return (
    <div
      className="cp-rise cp-card"
      style={{
        animationDelay: delay * 70 + "ms",
        background: "#fff",
        border: "1px solid #e2e8f0",
        borderRadius: 16,
        padding: 22,
        marginBottom: 16,
        boxShadow: "0 1px 2px rgba(15,23,42,0.03), 0 10px 24px -16px rgba(15,23,42,0.14)",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 800, color: "#4a0080", marginBottom: 16 }}>
        {icon} {title}
      </div>
      {children}
    </div>
  );
}

function IconTile({ children, bg, color }: { children: React.ReactNode; bg: string; color: string }) {
  return (
    <div
      style={{
        width: 38, height: 38, borderRadius: 11, background: bg, color,
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        border: "1px solid rgba(0,0,0,0.04)",
      }}
    >
      {children}
    </div>
  );
}

function Field({ icon, bg, color, label, value }: { icon: React.ReactNode; bg: string; color: string; label: string; value: string }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, background: "#f8fafc", borderRadius: 12, padding: "12px 14px" }}>
      <IconTile bg={bg} color={color}>{icon}</IconTile>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 0.5 }}>{label}</div>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1e293b", marginTop: 1 }}>{value}</div>
      </div>
    </div>
  );
}

export default function CompanyDetailPage() {
  const router = useRouter();
  const [company, setCompany] = useState<Company | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCompany();
  }, []);

  const fetchCompany = async () => {
    try {
      const response = await clientPortalApi.getCompany();
      const data = response.data || response;
      setCompany(data);
    } catch (error) {
      toast.error("Failed to load company data");
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className={styles.errorContainer}>
        <p className={styles.errorMessage}>Loading company information...</p>
      </div>
    );
  }

  if (!company) {
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>{"\u26a0\ufe0f"}</div>
        <h3 className={styles.errorTitle}>No company data found</h3>
      </div>
    );
  }

  const scopeItems = parseScopeItems(company.scope_of_work);

  return (
    <div className={styles.container}>
      <style>{PREMIUM_CSS}</style>

      <button
        className={styles.secondaryBtn}
        onClick={() => router.push("/client/dashboard/company")}
        style={{ marginBottom: 16 }}
      >
        <FiArrowLeft size={14} /> Back to client info
      </button>

      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <h1 className={styles.title}>{company.name}</h1>
            <span style={{ background: "rgba(255,255,255,0.2)", color: "#fff", fontSize: 11, fontWeight: 700, padding: "3px 10px", borderRadius: 99, whiteSpace: "nowrap" }}>
              Active client
            </span>
          </div>
          <p className={styles.subtitle}>{company.company_code}</p>
        </div>
      </div>

      <Card title="Contact information" icon={<FiMail size={14} />} delay={0}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field icon={<FiMail size={16} />} bg="#eff6ff" color="#1d4ed8" label="Email" value={company.email || "N/A"} />
          <Field icon={<FiPhone size={16} />} bg="#f0fdfa" color="#0f766e" label="Mobile" value={company.mobile || "N/A"} />
          <Field icon={<FiPhone size={16} />} bg="#f0fdfa" color="#0f766e" label="Telephone" value={company.telephone || "N/A"} />
          <Field icon={<FiPhone size={16} />} bg="#f0fdfa" color="#0f766e" label="Fax" value={company.fax || "N/A"} />
          <Field icon={<FiGlobe size={16} />} bg="#eef2ff" color="#4338ca" label="Country" value={company.country?.name || "N/A"} />
        </div>
      </Card>

      <Card title="Address" icon={<FiMapPin size={14} />} delay={1}>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field icon={<FiMapPin size={16} />} bg="#fffbeb" color="#d97706" label="Full address" value={company.address || "N/A"} />
          <Field icon={<FiMapPin size={16} />} bg="#fffbeb" color="#d97706" label="City" value={company.city || "N/A"} />
        </div>
      </Card>

      <Card title="Registration and licensing" icon={<FiHash size={14} />} delay={2}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field icon={<FiHash size={16} />} bg="#f5f3ff" color="#6d28d9" label="Trade license no." value={company.trade_license_no || "N/A"} />
          <Field icon={<FiHash size={16} />} bg="#f5f3ff" color="#6d28d9" label="Reference number" value={company.reference_number || "N/A"} />
          <Field icon={<FiCalendar size={16} />} bg="#fef2f2" color="#b91c1c" label="Validity" value={company.validity || "N/A"} />
          <Field icon={<FiAward size={16} />} bg="#f0fdfa" color="#0f766e" label="Certification body" value={company.certification_body || "N/A"} />
          <Field icon={<FiUsers size={16} />} bg="#eff6ff" color="#1d4ed8" label="Client group" value={company.client_group || "N/A"} />
        </div>
      </Card>

      {scopeItems.length > 0 && (
        <Card title="Scope of work" icon={<FiFileText size={14} />} delay={3}>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {scopeItems.map((item, idx) => (
              <div
                key={idx}
                className="cp-scope-row"
                style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "9px 8px", borderRadius: 8 }}
              >
                <span style={{ color: "#6a0dad", marginTop: 2, flexShrink: 0 }}>
                  <FiPlay size={11} style={{ fill: "currentColor" }} />
                </span>
                <span style={{ fontSize: 13.5, color: "#334155", lineHeight: 1.5 }}>{item}</span>
              </div>
            ))}
          </div>
        </Card>
      )}

      {company.standards && company.standards.length > 0 && (
        <Card title="Applicable standards" icon={<FiAward size={14} />} delay={4}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {company.standards.map((std, idx) => (
              <span key={idx} className={styles.departmentTag}>
                {typeof std === "string" ? std : std.name || std.title}
              </span>
            ))}
          </div>
        </Card>
      )}

      <Card title="Documents" icon={<FiFolder size={14} />} delay={5}>
        {company.documents && company.documents.length > 0 ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {company.documents.map((doc, idx) => (
              <a
                key={idx}
                href={doc.filePath}
                target="_blank"
                rel="noreferrer"
                style={{
                  display: "flex", alignItems: "center", gap: 12, padding: "12px 14px",
                  border: "1px solid #e2e8f0", borderRadius: 12, textDecoration: "none", color: "inherit",
                }}
              >
                <IconTile bg="#eef2ff" color="#4338ca"><FiFileText size={15} /></IconTile>
                <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{doc.originalName}</span>
                <span style={{ color: "#94a3b8" }}><FiDownload size={14} /></span>
              </a>
            ))}
          </div>
        ) : (
          <div style={{ fontSize: 13, color: "#94a3b8", textAlign: "center", padding: "16px 0" }}>
            No documents uploaded yet
          </div>
        )}
      </Card>
    </div>
  );
}