'use client';

import React, { useRef, useState } from 'react';
import {
  FiArrowRight,
  FiEdit2,
  FiTrash2,
  FiMoreVertical,
  FiClipboard,
  FiDownload,
  FiChevronDown,
  FiChevronUp,
  FiFileText,
  FiExternalLink,
} from 'react-icons/fi';
import type { ClientRow } from '@/lib/api/types/clients.types';
import {
  CLIENT_SOURCE_CONFIG,
  CLIENT_TYPE_CONFIG,
  getStatusMeta,
  parseStandards,
  formatDateWithHint,
  avatarGradient,
  firstInitial,
  clientCode,
  hasSignedDoc,
  signedDocName,
} from '@/lib/api/mappers/clients.mappers';
import type { ButtonConfig, ColumnConfig } from './useClientsPermissions';

interface Props {
  row: ClientRow;
  visibleColumns: ColumnConfig[];
  rowButtons: ButtonConfig[];
  hasActionsColumn: boolean;
  mapColumnKeyToValue: (key: string, row: ClientRow) => any;
  onView: (row: ClientRow) => void;
  onEdit: (row: ClientRow) => void;
  onDelete: (row: ClientRow) => void;
  onAuditRequest: (row: ClientRow) => void;
  onExportRow: (row: ClientRow) => void;
  onOpenSignedDoc: (row: ClientRow) => void;
}

const MENU_WIDTH = 190;

const ACTION_META: Record<
  string,
  { label: string; icon: React.ReactNode; color: string }
> = {
  view: { label: 'View', icon: <FiArrowRight size={14} />, color: '#4338ca' },
  'view-all': { label: 'View', icon: <FiArrowRight size={14} />, color: '#4338ca' },
  edit: { label: 'Edit', icon: <FiEdit2 size={14} />, color: '#c2410c' },
  'audit-request': {
    label: 'Audit request',
    icon: <FiClipboard size={14} />,
    color: '#0f766e',
  },
  'signed-doc': {
    label: 'Signed doc',
    icon: <FiFileText size={14} />,
    color: '#2563eb',
  },
  export: { label: 'Export row', icon: <FiDownload size={14} />, color: '#166534' },
  delete: { label: 'Delete', icon: <FiTrash2 size={14} />, color: '#dc2626' },
};

// ─── Standards chips with "+N" popover, same UX as my-audits ───────────
function StandardsBadges({ raw }: { raw: string | null | undefined }) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
  const chipRef = useRef<HTMLButtonElement | null>(null);

  const list = parseStandards(raw);
  if (list.length === 0) {
    return <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>;
  }

  const first = list[0];
  const rest = list.slice(1);

  const handleToggle = () => {
    if (!open && chipRef.current) {
      const rect = chipRef.current.getBoundingClientRect();
      setPos({ top: rect.bottom + 4, left: rect.left });
    } else {
      setPos(null);
    }
    setOpen(!open);
  };

  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
      <span
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          padding: '3px 9px',
          borderRadius: 99,
          background: '#eef2ff',
          color: '#4338ca',
          fontSize: 11,
          fontWeight: 600,
          whiteSpace: 'nowrap',
          border: '1px solid #c7d2fe',
        }}
      >
        {first}
      </span>

      {rest.length > 0 && (
        <>
          <button
            ref={chipRef}
            type="button"
            onClick={handleToggle}
            title={list.join(', ')}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 3,
              padding: '3px 8px',
              borderRadius: 99,
              background: '#f3f4f6',
              color: '#4b5563',
              fontSize: 11,
              fontWeight: 700,
              border: '1px solid #e5e7eb',
              cursor: 'pointer',
              whiteSpace: 'nowrap',
            }}
          >
            +{rest.length}
            {open ? <FiChevronUp size={10} /> : <FiChevronDown size={10} />}
          </button>

          {open && pos && (
            <>
              <div
                onClick={() => {
                  setOpen(false);
                  setPos(null);
                }}
                style={{ position: 'fixed', inset: 0, zIndex: 9998 }}
              />
              <div
                style={{
                  position: 'fixed',
                  top: pos.top,
                  left: pos.left,
                  zIndex: 9999,
                  background: '#fff',
                  border: '1px solid #e5e7eb',
                  borderRadius: 8,
                  boxShadow: '0 10px 30px rgba(0,0,0,0.12)',
                  padding: 6,
                  minWidth: 180,
                  maxHeight: 240,
                  overflowY: 'auto',
                }}
              >
                <div
                  style={{
                    padding: '4px 8px',
                    fontSize: 10,
                    fontWeight: 700,
                    color: '#6b7280',
                    textTransform: 'uppercase',
                    letterSpacing: '0.05em',
                  }}
                >
                  All standards ({list.length})
                </div>
                {list.map((s, i) => (
                  <div key={`${s}-${i}`} style={{ padding: '6px 8px', fontSize: 12, color: '#374151' }}>
                    {s}
                  </div>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}

// ─── Signed document chip — click opens it, same flow as audit report ──
function SignedDocCell({
  row,
  onOpen,
}: {
  row: ClientRow;
  onOpen: (row: ClientRow) => void;
}) {
  const name = signedDocName(row);
  if (!hasSignedDoc(row) || !name) {
    // Surveillance rows / clients without an upload — that's the data.
    return <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>;
  }
  return (
    <button
      type="button"
      onClick={() => onOpen(row)}
      title={`Open ${name}`}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 5,
        padding: '3px 9px',
        borderRadius: 99,
        background: '#eff6ff',
        color: '#2563eb',
        border: '1px solid #bfdbfe',
        fontSize: 11,
        fontWeight: 600,
        cursor: 'pointer',
        maxWidth: 180,
        whiteSpace: 'nowrap',
      }}
      onMouseEnter={(e) => (e.currentTarget.style.background = '#dbeafe')}
      onMouseLeave={(e) => (e.currentTarget.style.background = '#eff6ff')}
    >
      <FiFileText size={12} style={{ flexShrink: 0 }} />
      <span
        style={{
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}
      >
        {name}
      </span>
      <FiExternalLink size={11} style={{ flexShrink: 0 }} />
    </button>
  );
}

function renderCell(
  col: ColumnConfig,
  row: ClientRow,
  value: any,
  onOpenSignedDoc: (row: ClientRow) => void,
) {
  // ── Company name + source chip ──
  if (col.key === 'company_name') {
    const name = row.company_name ?? '—';
    const src = CLIENT_SOURCE_CONFIG[row.source];
    return (
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 9, maxWidth: 280 }}>
        <div
          style={{
            width: 30,
            height: 30,
            borderRadius: 8,
            flexShrink: 0,
            background: avatarGradient(`${row.source}${row.id}`),
            color: '#fff',
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 12,
            fontWeight: 700,
          }}
        >
          {firstInitial(name)}
        </div>
        <div style={{ minWidth: 0 }}>
          <div
            title={name}
            style={{
              fontWeight: 600,
              fontSize: 13,
              color: '#111827',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {name}
          </div>
          <span
            style={{
              display: 'inline-block',
              marginTop: 4,
              padding: '2px 8px',
              borderRadius: 99,
              background: src.bg,
              color: src.color,
              border: `1px solid ${src.border}`,
              fontSize: 10,
              fontWeight: 700,
            }}
          >
            📁 {src.label}
          </span>
        </div>
      </div>
    );
  }

  // ── Code ──
  if (col.key === 'client_code') {
    return (
      <span
        style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 11,
          color: '#0f766e',
          fontWeight: 600,
          whiteSpace: 'nowrap',
        }}
      >
        {clientCode(row)}
      </span>
    );
  }

  // ── Record type ──
  if (col.key === 'client_type') {
    const cfg = CLIENT_TYPE_CONFIG[row.client_type];
    return (
      <span
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 5,
          padding: '4px 10px',
          borderRadius: 8,
          background: cfg.bg,
          color: cfg.color,
          border: `1px solid ${cfg.border}`,
          fontSize: 11,
          fontWeight: 700,
          whiteSpace: 'nowrap',
        }}
      >
        {cfg.icon} {cfg.label}
      </span>
    );
  }

  // ── Source on its own ──
  if (col.key === 'source') {
    const src = CLIENT_SOURCE_CONFIG[row.source];
    return (
      <span
        style={{
          padding: '3px 10px',
          borderRadius: 99,
          background: src.bg,
          color: src.color,
          border: `1px solid ${src.border}`,
          fontSize: 11,
          fontWeight: 700,
        }}
      >
        {src.label}
      </span>
    );
  }

  // ── Contact + designation ──
  if (col.key === 'contact_primary') {
    return (
      <div style={{ maxWidth: 180 }}>
        <div
          style={{
            fontSize: 12.5,
            fontWeight: 600,
            color: '#1f2937',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {row.contact_primary ?? '—'}
        </div>
        {row.designationpr && (
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 1 }}>
            {row.designationpr}
          </div>
        )}
      </div>
    );
  }

  // ── Standards ──
  if (col.key === 'standard_name') {
    return <StandardsBadges raw={row.standard_name} />;
  }

  // ── Signed document — name shown, click opens (audit-report style) ──
  if (col.key === 'signeddocsname' || col.key === 'signed_docs') {
    return <SignedDocCell row={row} onOpen={onOpenSignedDoc} />;
  }

  // ── Email + phone ──
  if (col.key === 'email_id') {
    return (
      <div style={{ maxWidth: 200 }}>
        {row.email_id ? (
          <a
            href={`mailto:${row.email_id}`}
            title={row.email_id}
            style={{
              fontSize: 12,
              color: '#2563eb',
              textDecoration: 'none',
              display: 'block',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {row.email_id}
          </a>
        ) : (
          <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>
        )}
        {(row.mobile_no || row.telephone) && (
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>
            {row.mobile_no || row.telephone}
          </div>
        )}
      </div>
    );
  }

  // ── Status ──
  if (col.key === 'status') {
    const st = getStatusMeta(row.status);
    return (
      <span
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 5,
          padding: '4px 10px',
          borderRadius: 99,
          background: st.bg,
          color: st.color,
          fontSize: 11,
          fontWeight: 600,
          whiteSpace: 'nowrap',
        }}
      >
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: st.dot }} />
        {st.label}
      </span>
    );
  }

  // ── Dates ──
  if (col.key === 'created_at' || col.key === 'updated_at') {
    const d = formatDateWithHint(value);
    return (
      <div>
        <div style={{ fontSize: 12, color: '#1f2937', whiteSpace: 'nowrap' }}>{d.main}</div>
        {d.hint && <div style={{ fontSize: 10.5, color: '#94a3b8' }}>{d.hint}</div>}
      </div>
    );
  }

  // ── Default text cell ──
  return (
    <span
      title={String(value ?? '')}
      style={{
        fontSize: 12.5,
        color: '#374151',
        display: 'inline-block',
        maxWidth: 190,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
      }}
    >
      {value ?? '—'}
    </span>
  );
}

export default function DynamicClientRow({
  row,
  visibleColumns,
  rowButtons,
  hasActionsColumn,
  mapColumnKeyToValue,
  onView,
  onEdit,
  onDelete,
  onAuditRequest,
  onExportRow,
  onOpenSignedDoc,
}: Props) {
  const [open, setOpen] = useState(false);
  const [menuPos, setMenuPos] = useState({ top: 0, bottom: 0, right: 0, left: 0 });
  const [openUp, setOpenUp] = useState(false);
  const btnRef = useRef<HTMLButtonElement | null>(null);

  const toggleMenu = () => {
    if (!open && btnRef.current) {
      const r = btnRef.current.getBoundingClientRect();
      const spaceBelow = window.innerHeight - r.bottom;
      setOpenUp(spaceBelow < 240);
      setMenuPos({ top: r.top, bottom: r.bottom, right: r.right, left: r.left });
    }
    setOpen((v) => !v);
  };

  const handle = (key: string) => {
    setOpen(false);
    switch (key) {
      case 'view':
      case 'view-all':
        return onView(row);
      case 'edit':
        return onEdit(row);
      case 'delete':
        return onDelete(row);
      case 'audit-request':
        return onAuditRequest(row);
      case 'export':
        return onExportRow(row);
      case 'signed-doc':
        return onOpenSignedDoc(row);
    }
  };

  const dataColumns = visibleColumns.filter((c) => c.key !== 'actions');

  // Hide the "Signed doc" menu item on rows that have nothing uploaded
  // (all surveillance rows, plus clients without a doc).
  const effectiveButtons = rowButtons.filter(
    (b) => b.key !== 'signed-doc' || hasSignedDoc(row),
  );

  return (
    <tr
      style={{ borderBottom: '1px solid #f1f5f9', transition: 'background 0.1s' }}
      onMouseEnter={(e) => (e.currentTarget.style.background = '#f8fafc')}
      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
    >
      {dataColumns.map((col) => (
        <td key={col.key} style={{ padding: '12px 10px', verticalAlign: 'top' }}>
          {renderCell(col, row, mapColumnKeyToValue(col.key, row), onOpenSignedDoc)}
        </td>
      ))}

      {hasActionsColumn && (
        <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
          <div style={{ position: 'relative', display: 'inline-block' }}>
            <button
              ref={btnRef}
              onClick={toggleMenu}
              title="Actions"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 30,
                height: 30,
                borderRadius: 6,
                border: '1px solid #e2e8f0',
                background: open ? '#f1f5f9' : '#fff',
                color: '#475569',
                cursor: 'pointer',
                padding: 0,
              }}
            >
              <FiMoreVertical size={16} />
            </button>

            {open && (
              <>
                <div
                  onClick={() => setOpen(false)}
                  style={{ position: 'fixed', inset: 0, zIndex: 990 }}
                />
                <div
                  style={{
                    position: 'fixed',
                    ...(openUp
                      ? { bottom: window.innerHeight - menuPos.top + 6 }
                      : { top: menuPos.bottom + 6 }),
                    left: Math.max(8, menuPos.right - MENU_WIDTH),
                    zIndex: 1000,
                    width: MENU_WIDTH,
                    background: '#fff',
                    border: '1px solid #e2e8f0',
                    borderRadius: 8,
                    boxShadow: '0 8px 24px rgba(15,23,42,0.12)',
                    padding: 4,
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 2,
                  }}
                >
                  {effectiveButtons.length === 0 && (
                    <span style={{ fontSize: 11, color: '#9ca3af', padding: '8px 10px' }}>
                      No actions
                    </span>
                  )}
                  {effectiveButtons.map((btn) => {
                    const meta = ACTION_META[btn.key];
                    if (!meta) return null;
                    return (
                      <button
                        key={btn.key}
                        onClick={() => handle(btn.key)}
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: 8,
                          width: '100%',
                          textAlign: 'left',
                          padding: '8px 10px',
                          borderRadius: 6,
                          border: 'none',
                          background: 'transparent',
                          color: meta.color,
                          fontSize: 12,
                          fontWeight: 600,
                          cursor: 'pointer',
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = '#f8fafc';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'transparent';
                        }}
                      >
                        {meta.icon} {btn.label || meta.label}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </td>
      )}
    </tr>
  );
}
