"use client";

import React, { useState } from "react";
import styles from "../../commonstyle/FormStyles.module.css";
import type { CompanyRow } from "@/lib/api/types/company.types";
import { StandardsBadge } from "../components/companies/StandardsBadge";
// 🆕 Portal access panel + invite modal
import PortalAccessPanel from "./PortalAccessPanel";
import InviteClientModal from "./InviteClientModal";

interface Props {
  row: CompanyRow | null;
  onClose: () => void;
  onEdit?: (row: CompanyRow) => void;
}

function SectionHeader({ title }: { title: string }) {
  return (
    <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
      <span className={styles.sectionDot} />
      {title}
    </div>
  );
}

function Field({
  label,
  value,
  mono = false,
  fullWidth = false,
}: {
  label: string;
  value?: string | null;
  mono?: boolean;
  fullWidth?: boolean;
}) {
  return (
    <div
      className={
        fullWidth ? `${styles.formGroup} ${styles.full}` : styles.formGroup
      }
    >
      <label className={styles.label}>{label}</label>
      <div
        style={{
          padding: "8px 12px",
          borderRadius: 8,
          border: "1px solid #e5e7eb",
          backgroundColor: "#f9fafb",
          fontSize: 13,
          color: value ? "#0f172a" : "#9ca3af",
          fontFamily: mono ? "'IBM Plex Mono', monospace" : "inherit",
          minHeight: 36,
          lineHeight: 1.5,
          whiteSpace: "pre-line",
        }}
      >
        {value || "—"}
      </div>
    </div>
  );
}

export default function CompanyViewModal({ row, onClose, onEdit }: Props) {
  // 🆕 State for the invite modal (launched from PortalAccessPanel)
  const [showInvite, setShowInvite] = useState(false);

  if (!row) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 860 }}
      >
        {/* ── Header ── */}
        <div
          className={styles.modalHeader}
          style={{
            background:
              "linear-gradient(135deg, #0c4a6e 0%, #0369a1 50%, #0ea5e9 100%)",
          }}
        >
          <div>
            <p
              className={styles.modalSubtitle}
              style={{
                color: "rgba(255,255,255,0.7)",
                marginBottom: 2,
                marginLeft: 0,
              }}
            >
              Company Details
            </p>
            <h2
              className={styles.modalTitle}
              style={{
                color: "#fff",
                fontFamily: "'IBM Plex Mono', monospace",
              }}
            >
              {row.name || "—"}
            </h2>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            {/* 🆕 Client status badge */}
            {(row as any).client_status && (
              <span
                style={{
                  padding: "4px 12px",
                  borderRadius: 99,
                  fontSize: 11,
                  fontWeight: 700,
                  backgroundColor:
                    (row as any).client_status === "ACTIVE"
                      ? "rgba(34, 197, 94, 0.3)"
                      : (row as any).client_status === "INACTIVE"
                        ? "rgba(239, 68, 68, 0.3)"
                        : "rgba(255,255,255,0.2)",
                  color: "#fff",
                }}
              >
                {(row as any).client_status}
              </span>
            )}
            <span
              style={{
                padding: "4px 12px",
                borderRadius: 99,
                fontSize: 11,
                fontWeight: 700,
                backgroundColor: "rgba(255,255,255,0.2)",
                color: "#fff",
                fontFamily: "'IBM Plex Mono', monospace",
              }}
            >
              {row.company_code}
            </span>
            <button
              className={styles.closeBtn}
              onClick={onClose}
              type="button"
              style={{
                color: "#fff",
                background: "rgba(255,255,255,0.2)",
                border: "none",
              }}
            >
              ✕
            </button>
          </div>
        </div>

        {/* ── Status strip ── */}
        <div
          style={{
            padding: "8px 24px",
            backgroundColor: row.validity ? "#ecfdf5" : "#f3f4f6",
            borderBottom: "1px solid #e2e8f0",
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <span
            style={{
              width: 8,
              height: 8,
              borderRadius: "50%",
              backgroundColor: row.validity ? "#10b981" : "#9ca3af",
              display: "inline-block",
            }}
          />
          <span
            style={{
              fontSize: 12,
              fontWeight: 700,
              color: row.validity ? "#065f46" : "#6b7280",
            }}
          >
            {row.validity ? `Valid · ${row.validity}` : "No active validity"}
          </span>
          {row.city && (
            <>
              <span style={{ color: "#cbd5e1", fontSize: 12 }}>·</span>
              <span style={{ fontSize: 12, color: "#64748b", fontWeight: 500 }}>
                📍 {row.city.trim()}
              </span>
            </>
          )}
          {row.standards?.length > 0 && (
            <span style={{ marginLeft: "auto" }}>
              <span
                style={{
                  fontSize: 11,
                  color: "#64748b",
                  fontWeight: 500,
                  textTransform: "uppercase",
                  letterSpacing: "0.05em",
                }}
              >
                {row.standards.length} Standard
                {row.standards.length > 1 ? "s" : ""}
              </span>
            </span>
          )}
        </div>

        {/* ── Body ── */}
        <div className={styles.formBody}>
          <SectionHeader title="🏢 Company Information" />
          <div className={styles.grid2}>
            <Field label="Company Name" value={row.name} fullWidth />
            <Field label="Company Code" value={row.company_code} mono />
            {/* ✅ NEW — Client Group (which internal team handles this client) */}
            <Field label="Client Group" value={(row as any).client_group} />
            <Field
              label="Certification Body"
              value={row.certification_body}
            />
            <Field label="Validity" value={row.validity} />
          </div>

          <SectionHeader title="👤 Contact Details" />
          <div className={styles.grid2}>
            <Field label="Contact Person" value={row.contact_person} />
            <Field label="Designation" value={row.designation} />
            <Field label="Email" value={row.email} mono />
            <Field label="Mobile" value={row.mobile} mono />
          </div>

          <SectionHeader title="📍 Address" />
          <div className={styles.grid2}>
            <Field label="City" value={row.city?.trim()} />
            <Field label="Address" value={(row as any).address} fullWidth />
          </div>

          {row.standards?.length > 0 && (
            <>
              <SectionHeader title="📜 ISO Standards" />
              <div
                style={{
                  padding: "14px",
                  borderRadius: 10,
                  backgroundColor: "#f9fafb",
                  border: "1px solid #e5e7eb",
                }}
              >
                <StandardsBadge standards={row.standards} size="md" />
              </div>
            </>
          )}

          {row.scope_of_work && (
            <>
              <SectionHeader title="📋 Scope of Work" />
              <div
                style={{
                  padding: "14px",
                  borderRadius: 10,
                  backgroundColor: "#f9fafb",
                  border: "1px solid #e5e7eb",
                  fontSize: 13,
                  color: "#374151",
                  whiteSpace: "pre-line",
                  lineHeight: 1.6,
                }}
              >
                {row.scope_of_work.trim()}
              </div>
            </>
          )}

          {/* ═══════════════════════════════════════════════════════════════
              🆕 ISSUE 5 & 6 — Portal access panel
              Shows all portal users for this company with
              enable/disable/invite/disable-all controls.
              ═══════════════════════════════════════════════════════════════ */}
          <SectionHeader title="🔐 Client Portal Access" />
          <div
            style={{
              padding: "14px",
              borderRadius: 10,
              backgroundColor: "#f9fafb",
              border: "1px solid #e5e7eb",
            }}
          >
            <PortalAccessPanel
              companyId={row.id}
              companyName={row.name}
              onInviteClick={() => setShowInvite(true)}
            />
          </div>

          <SectionHeader title="🕒 Audit Trail" />
          <div className={styles.grid2}>
            <Field
              label="Created At"
              value={
                (row as any).created_at
                  ? new Date((row as any).created_at).toLocaleString("en-GB")
                  : null
              }
            />
            <Field
              label="Last Updated"
              value={
                (row as any).updated_at
                  ? new Date((row as any).updated_at).toLocaleString("en-GB")
                  : null
              }
            />
          </div>
        </div>

        {/* ── Footer ── */}
        <div className={styles.modalFooter}>
          <button type="button" onClick={onClose} className={styles.cancelBtn}>
            Close
          </button>

          {onEdit && (
            <button
              type="button"
              onClick={() => {
                onEdit(row);
                onClose();
              }}
              className={styles.btnSubmit}
              style={{
                background:
                  "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
                border: "none",
                color: "#fff",
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              ✏️ Edit Company
            </button>
          )}
        </div>
      </div>

      {/* 🆕 Invite modal — launched from PortalAccessPanel's "Invite" button */}
      <InviteClientModal
        isOpen={showInvite}
        company={row}
        onClose={() => setShowInvite(false)}
      />
    </div>
  );
}