"use client";

import React, { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import toast from "react-hot-toast";
import {
  FiArrowLeft, FiMapPin, FiHash, FiPrinter, FiPlay, FiFileText,
  FiAward, FiFolder, FiDownload, FiGlobe,
} from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";

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[];
}

// Confirmed via browser console: the real separator is U+F0D8, a Private
// Use Area code point (U+E000-U+F8FF) - almost certainly a Wingdings-style
// bullet from a Word document that lost its font mapping when copied into
// plain text. No standard font can render it, which is why it always
// showed as a blank box regardless of which system displayed it.
function parseScopeItems(text?: string): string[] {
  if (!text) return [];
  return text
    .split(/[\uE000-\uF8FF]+/gu)
    .map((s) => s.trim())
    .filter(Boolean);
}

function Field({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "9px 0", borderBottom: "1px solid #f1f5f9" }}>
      <span style={{ fontSize: 12.5, color: "#7c3aed", fontWeight: 500 }}>{label}</span>
      <span style={{ fontSize: 13, color: "#1e293b", fontWeight: 700, textAlign: "right" }}>{value}</span>
    </div>
  );
}

function InfoBox({ title, accent, children }: { title: string; accent: string; children: React.ReactNode }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 12, padding: "16px 18px", borderLeft: "3px solid " + accent }}>
      <div style={{ fontSize: 11, fontWeight: 800, color: accent, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 10 }}>
        {title}
      </div>
      {children}
    </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 style={{ padding: 60, textAlign: "center", color: "#94a3b8" }}>
        Loading company information...
      </div>
    );
  }

  if (!company) {
    return (
      <div style={{ padding: 60, textAlign: "center" }}>
        <h3>No company data found</h3>
      </div>
    );
  }

  const scopeItems = parseScopeItems(company.scope_of_work);
  const standardsCount = company.standards?.length || 0;

  return (
    <div className="cd-root">
      <style>{CSS}</style>

      <button onClick={() => router.push("/client/dashboard/company")} className="cd-back">
        <FiArrowLeft size={14} /> Back to client info
      </button>

      <header className="cd-hero">
        <div className="cd-hero-rule" />
        <div className="cd-hero-inner">
          <div className="cd-hero-left">
            <div className="cd-meta-top">
              <span className="cd-code">{company.company_code}</span>
              <span className="cd-dot" />
              <span className="cd-type"><FiHash size={12} /> Client profile</span>
            </div>
            <h1 className="cd-title">{company.name}</h1>
            <div className="cd-meta-row">
              {company.city && (
                <span className="cd-chip"><FiMapPin size={12} /> {company.city}</span>
              )}
              {company.country?.name && (
                <span className="cd-chip"><FiGlobe size={12} /> {company.country.name}</span>
              )}
              {standardsCount > 0 && (
                <span className="cd-chip"><FiAward size={12} /> {standardsCount} standard{standardsCount === 1 ? "" : "s"}</span>
              )}
            </div>
          </div>
          <div className="cd-hero-right">
            <span className="cd-status"><span className="cd-status-dot" /> Active client</span>
            <button className="cd-print" onClick={() => window.print()}>
              <FiPrinter size={14} /> Print
            </button>
          </div>
        </div>
      </header>

      <div className="cd-stats">
        <div className="cd-stat">
          <div className="cd-stat-label">City</div>
          <div className="cd-stat-value">{company.city || "\u2014"}</div>
        </div>
        <div className="cd-stat">
          <div className="cd-stat-label">Country</div>
          <div className="cd-stat-value">{company.country?.name || "\u2014"}</div>
        </div>
        <div className="cd-stat">
          <div className="cd-stat-label">Certification body</div>
          <div className="cd-stat-value">{company.certification_body || "\u2014"}</div>
        </div>
        <div className="cd-stat">
          <div className="cd-stat-label">Client group</div>
          <div className="cd-stat-value">{company.client_group || "\u2014"}</div>
        </div>
      </div>

      <div className="cd-grid2">
        <InfoBox title="Contact" accent="#4338ca">
          <Field label="Email" value={company.email || "N/A"} />
          <Field label="Mobile" value={company.mobile || "N/A"} />
          <Field label="Telephone" value={company.telephone || "N/A"} />
          <Field label="Fax" value={company.fax || "N/A"} />
        </InfoBox>
        <InfoBox title="Registration and licensing" accent="#0f766e">
          <Field label="Trade license no." value={company.trade_license_no || "N/A"} />
          <Field label="Reference number" value={company.reference_number || "N/A"} />
          <Field label="Validity" value={company.validity || "N/A"} />
        </InfoBox>
      </div>

      <InfoBox title="Address" accent="#d97706">
        <Field label="Full address" value={company.address || "N/A"} />
        <Field label="City" value={company.city || "N/A"} />
      </InfoBox>

      {scopeItems.length > 0 && (
        <div className="cd-card">
          <div className="cd-card-title"><FiFileText size={14} /> Scope of work</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {scopeItems.map((item, idx) => (
              <div key={idx} className="cd-scope-row">
                <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>
        </div>
      )}

      {company.standards && company.standards.length > 0 && (
        <div className="cd-card">
          <div className="cd-card-title"><FiAward size={14} /> Applicable standards</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {company.standards.map((std, idx) => (
              <span key={idx} className="cd-standard-chip">
                {typeof std === "string" ? std : std.name || std.title}
              </span>
            ))}
          </div>
        </div>
      )}

      <div className="cd-card">
        <div className="cd-card-title"><FiFolder size={14} /> Documents</div>
        {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" className="cd-doc-row">
                <span className="cd-doc-icon"><FiFileText size={15} /></span>
                <span className="cd-doc-label">{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>
        )}
      </div>
    </div>
  );
}

const CSS = `
.cd-root {
  --ink: #160a33;
  --ink-2: #2a0f57;
  --line: #ece8f4;
  --muted: #79728f;
  color: #211a3a;
  font-variant-numeric: tabular-nums;
}
.cd-root *, .cd-root *::before, .cd-root *::after { box-sizing: border-box; }

.cd-back {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 6px 10px; margin-bottom: 12px;
  background: transparent; border: none; border-radius: 8px;
  color: var(--muted); cursor: pointer; font-size: 13px; font-weight: 600;
}
.cd-back:hover { color: var(--ink); background: #f3f0fa; }

.cd-hero {
  position: relative; overflow: hidden; border-radius: 18px; margin-bottom: 16px;
  background:
    radial-gradient(120% 170% at 100% 0%, rgba(124,58,237,0.42) 0%, rgba(124,58,237,0) 55%),
    linear-gradient(135deg, var(--ink) 0%, var(--ink-2) 100%);
  color: #fff;
  box-shadow: 0 10px 30px -14px rgba(22,10,51,0.55);
}
.cd-hero-rule { height: 3px; background: linear-gradient(90deg, #d4a017 0%, #f0c14b 40%, rgba(240,193,75,0) 100%); }
.cd-hero-inner { display: flex; justify-content: space-between; align-items: flex-start; gap: 18px; padding: 22px 24px; flex-wrap: wrap; }
.cd-hero-left { flex: 1; min-width: 0; }
.cd-meta-top { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; font-size: 12px; color: rgba(255,255,255,0.7); margin-bottom: 9px; }
.cd-code { font-family: 'JetBrains Mono', monospace; font-size: 11.5px; font-weight: 600; letter-spacing: 0.02em; color: #f0e9ff; background: rgba(255,255,255,0.10); border: 1px solid rgba(255,255,255,0.18); padding: 3px 9px; border-radius: 7px; }
.cd-type { display: inline-flex; align-items: center; gap: 5px; }
.cd-dot { width: 3px; height: 3px; border-radius: 50%; background: rgba(255,255,255,0.4); }
.cd-title { margin: 0; font-size: 23px; line-height: 1.12; font-weight: 750; letter-spacing: -0.02em; color: #fff; }
.cd-meta-row { margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap; }
.cd-chip { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 550; color: rgba(255,255,255,0.82); background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12); padding: 5px 11px; border-radius: 999px; }
.cd-hero-right { display: flex; flex-direction: column; align-items: flex-end; gap: 12px; }
.cd-status { display: inline-flex; align-items: center; gap: 6px; padding: 5px 13px; border-radius: 999px; font-size: 12px; font-weight: 700; background: #dcfce7; color: #166534; }
.cd-status-dot { width: 7px; height: 7px; border-radius: 50%; background: #16a34a; }

.cd-print { display: inline-flex; align-items: center; gap: 7px; padding: 9px 16px; border-radius: 9px; border: 1px solid rgba(255,255,255,0.3); background: rgba(255,255,255,0.12); color: #fff; font-size: 13px; font-weight: 600; cursor: pointer; }
.cd-print:hover { background: rgba(255,255,255,0.2); }

.cd-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px; }
.cd-stat { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 12px 14px; }
.cd-stat-label { font-size: 10px; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 3px; }
.cd-stat-value { font-size: 13.5px; font-weight: 700; color: #1e293b; }

.cd-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 14px; }

.cd-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; padding: 22px; margin-bottom: 14px; box-shadow: 0 1px 2px rgba(15,23,42,0.03), 0 10px 24px -16px rgba(15,23,42,0.14); }
.cd-card-title { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 800; color: var(--ink-2); margin-bottom: 16px; }

.cd-scope-row { display: flex; align-items: flex-start; gap: 10px; padding: 9px 8px; border-radius: 8px; }
.cd-scope-row:hover { background: #f8fafc; }

.cd-standard-chip { font-size: 12px; font-weight: 600; color: #4338ca; background: #eef2ff; border: 1px solid #c7d2fe; padding: 4px 12px; border-radius: 999px; }

.cd-doc-row { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border: 1px solid #e2e8f0; border-radius: 12px; text-decoration: none; color: inherit; }
.cd-doc-row:hover { background: #f8fafc; }
.cd-doc-icon { width: 34px; height: 34px; border-radius: 9px; background: #eef2ff; color: #4338ca; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.cd-doc-label { flex: 1; font-size: 13px; font-weight: 600; color: #1e293b; }

@media (max-width: 720px) {
  .cd-hero-inner { flex-direction: column; }
  .cd-hero-right { align-items: stretch; width: 100%; }
  .cd-grid2 { grid-template-columns: 1fr; }
  .cd-stats { grid-template-columns: 1fr 1fr; }
}
@media print {
  .cd-back, .cd-print { display: none; }
}
`;