import { useState, useEffect, Fragment } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
import { useCompanies, useDeleteCompany, useCompanyContacts } from '../hooks';
import { CompanyFormModal } from './CompanyFormModal';
import type { Company, Contact, CompaniesQueryParams, ContactType, EntityStatus } from '../types';
import { ENTITY_STATUS_LABELS } from '../types';
import styles from './CompaniesPage.module.css';

const thStyle: React.CSSProperties = {
  padding: '0.75rem 1rem',
  textAlign: 'left',
  fontSize: '0.75rem',
  textTransform: 'uppercase',
  color: 'var(--color-text-muted)',
};

const tdStyle: React.CSSProperties = {
  padding: '0.75rem 1rem',
  fontSize: '0.875rem',
  color: 'var(--color-text-secondary)',
};

// --------------------------------------------------------
// Kontakt-Anzeigename
// --------------------------------------------------------
function contactDisplayName(c: Contact): string {
  if (c.type === 'ORGANIZATION') return c.companyName ?? '—';
  return [c.firstName, c.lastName].filter(Boolean).join(' ') || '—';
}

const TYPE_LABELS: Record<ContactType, string> = {
  PERSON: 'Person',
  ORGANIZATION: 'Organisation',
};

// --------------------------------------------------------
// ContactSubRows — lazy-loaded Kontakte eines Unternehmens
// --------------------------------------------------------
function ContactSubRows({ companyId }: { companyId: string }) {
  const navigate = useNavigate();
  const { data, isLoading, error } = useCompanyContacts(companyId, true);

  if (isLoading) {
    return (
      <tr className={styles.subRow}>
        <td colSpan={9} className={styles.subRowLoading}>
          Kontakte laden...
        </td>
      </tr>
    );
  }

  if (error) {
    return (
      <tr className={styles.subRow}>
        <td colSpan={9} className={styles.subRowError}>
          Fehler beim Laden der Kontakte
        </td>
      </tr>
    );
  }

  const contacts = data?.data ?? [];

  if (contacts.length === 0) {
    return (
      <tr className={styles.subRow}>
        <td colSpan={9} className={styles.subRowEmpty}>
          Keine Kontakte vorhanden
        </td>
      </tr>
    );
  }

  return (
    <>
      {contacts.map((contact) => (
        <tr
          key={contact.id}
          className={styles.subRow}
          onClick={() => navigate(`/crm/contacts/${contact.id}`)}
        >
          {/* Indent / Connector */}
          <td className={styles.subRowIndent}>
            <span className={styles.subRowConnector} />
          </td>
          {/* Name */}
          <td className={styles.subRowCell} style={{ fontWeight: 500 }}>
            {contactDisplayName(contact)}
          </td>
          {/* Position (anstelle Branche) */}
          <td className={styles.subRowCell}>
            {contact.position ?? '—'}
          </td>
          {/* E-Mail */}
          <td className={styles.subRowCell}>
            {contact.email ?? '—'}
          </td>
          {/* Telefon (anstelle Kontakte-Zahl) */}
          <td className={styles.subRowCell}>
            {contact.phone ?? contact.mobile ?? '—'}
          </td>
          {/* Typ-Badge (anstelle Vorgaenge) */}
          <td className={styles.subRowCell} style={{ textAlign: 'center' }}>
            <span className={styles.typeBadge} data-type={contact.type}>
              {TYPE_LABELS[contact.type] ?? '—'}
            </span>
          </td>
          {/* Status */}
          <td className={styles.subRowCell}>
            <span
              style={{
                display: 'inline-block',
                width: 8,
                height: 8,
                borderRadius: '50%',
                background: ((contact as Contact & { status?: EntityStatus }).status ?? (contact.isActive ? 'ACTIVE' : 'INACTIVE')) === 'ACTIVE'
                  ? 'var(--color-success)'
                  : ((contact as Contact & { status?: EntityStatus }).status ?? '') === 'BLOCKED'
                    ? '#991b1b'
                    : 'var(--color-error)',
              }}
              title={ENTITY_STATUS_LABELS[((contact as Contact & { status?: EntityStatus }).status ?? (contact.isActive ? 'ACTIVE' : 'INACTIVE')) as EntityStatus] ?? 'Unbekannt'}
            />
          </td>
          {/* Leere Aktionen-Spalte */}
          <td className={styles.subRowCell} />
        </tr>
      ))}
    </>
  );
}

// --------------------------------------------------------
// CompaniesPage — Hauptkomponente
// --------------------------------------------------------
export function CompaniesPage() {
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch] = useState('');
  const [isCreateOpen, setCreateOpen] = useState(false);
  const [editingCompany, setEditingCompany] = useState<Company | null>(null);
  const [deletingCompany, setDeletingCompany] = useState<Company | null>(null);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());

  // Debounced search
  useEffect(() => {
    const t = setTimeout(() => {
      setSearch(searchInput);
      setPage(1);
    }, 300);
    return () => clearTimeout(t);
  }, [searchInput]);

  // Reset expanded rows on page change
  useEffect(() => {
    setExpandedIds(new Set());
  }, [page]);

  const params: CompaniesQueryParams = {
    page,
    pageSize: 25,
    ...(search ? { search } : {}),
    sort: 'createdAt',
    order: 'desc',
  };

  const { data, isLoading, error } = useCompanies(params);
  const deleteMutation = useDeleteCompany();

  const toggleExpand = (companyId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(companyId)) {
        next.delete(companyId);
      } else {
        next.add(companyId);
      }
      return next;
    });
  };

  if (isLoading) return <p>Laden...</p>;
  if (error)
    return (
      <p style={{ color: 'var(--color-error)' }}>
        Fehler beim Laden der Unternehmen
      </p>
    );

  const companies = data?.data ?? [];
  const pagination = data?.pagination;

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '1.5rem',
        }}
      >
        <h1 style={{ fontSize: '1.5rem', fontWeight: 600 }}>Unternehmen</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <span
            style={{
              color: 'var(--color-text-muted)',
              fontSize: '0.875rem',
            }}
          >
            {pagination?.total ?? 0} Unternehmen gesamt
          </span>
          <button
            onClick={() => setCreateOpen(true)}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-primary)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: 'pointer',
            }}
          >
            + Neues Unternehmen
          </button>
        </div>
      </div>

      {/* Filterleiste */}
      <div className={styles.filterBar}>
        <input
          type="search"
          placeholder="Suche nach Name, Branche, E-Mail, Stadt..."
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          className={styles.searchInput}
        />
      </div>

      {/* Tabelle */}
      <div
        style={{
          background: 'var(--color-bg-card)',
          borderRadius: 'var(--radius-md)',
          boxShadow: 'var(--shadow-sm)',
          border: '1px solid var(--color-border)',
          overflow: 'hidden',
        }}
      >
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr
              style={{
                borderBottom: '1px solid var(--color-border)',
                background: 'var(--color-bg)',
              }}
            >
              <th style={{ ...thStyle, width: '40px', padding: '0.75rem 0.5rem' }} />
              <th style={thStyle}>Name</th>
              <th style={thStyle}>Branche</th>
              <th style={thStyle}>E-Mail</th>
              <th style={{ ...thStyle, textAlign: 'center' }}>Kontakte</th>
              <th style={{ ...thStyle, textAlign: 'center' }}>Vorgänge</th>
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {companies.length === 0 && (
              <tr>
                <td
                  colSpan={9}
                  style={{
                    padding: '2rem',
                    textAlign: 'center',
                    color: 'var(--color-text-muted)',
                  }}
                >
                  Keine Unternehmen gefunden
                </td>
              </tr>
            )}
            {companies.map((company) => {
              const contactCount = company._count?.contacts ?? 0;
              const isExpanded = expandedIds.has(company.id);

              return (
                <Fragment key={company.id}>
                  {/* Company Row */}
                  <tr
                    className={isExpanded ? styles.expandedRow : undefined}
                    style={{
                      borderBottom: '1px solid var(--color-border)',
                      cursor: 'pointer',
                    }}
                    onClick={() => navigate(`/crm/companies/${company.id}`)}
                  >
                    {/* Expand Button */}
                    <td
                      style={{ padding: '0.75rem 0.5rem', textAlign: 'center', width: '40px' }}
                      onClick={(e) => contactCount > 0 && toggleExpand(company.id, e)}
                    >
                      {contactCount > 0 && (
                        <button
                          className={styles.expandBtn}
                          aria-expanded={isExpanded}
                          aria-label={isExpanded ? 'Kontakte einklappen' : 'Kontakte aufklappen'}
                        >
                          <span
                            className={styles.expandIcon}
                            style={{
                              transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)',
                            }}
                          >
                            &#9654;
                          </span>
                        </button>
                      )}
                    </td>
                    {/* Name */}
                    <td
                      style={{
                        padding: '0.75rem 1rem',
                        fontSize: '0.875rem',
                        fontWeight: 500,
                      }}
                    >
                      {company.name}
                    </td>
                    {/* Branche */}
                    <td style={tdStyle}>
                      {company.industry ?? '—'}
                    </td>
                    {/* E-Mail */}
                    <td style={tdStyle}>
                      {company.email ?? '—'}
                    </td>
                    {/* Kontakte */}
                    <td style={{ ...tdStyle, textAlign: 'center' }}>
                      {contactCount}
                    </td>
                    {/* Vorgaenge */}
                    <td style={{ ...tdStyle, textAlign: 'center' }}>
                      {company._count?.deals ?? 0}
                    </td>
                    {/* Status */}
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <span
                        style={{
                          display: 'inline-block',
                          width: 8,
                          height: 8,
                          borderRadius: '50%',
                          background: (company.status ?? (company.isActive ? 'ACTIVE' : 'INACTIVE')) === 'ACTIVE'
                            ? 'var(--color-success)'
                            : (company.status ?? '') === 'BLOCKED'
                              ? '#991b1b'
                              : 'var(--color-error)',
                        }}
                        title={ENTITY_STATUS_LABELS[(company.status ?? (company.isActive ? 'ACTIVE' : 'INACTIVE')) as EntityStatus] ?? 'Unbekannt'}
                      />
                    </td>
                    {/* Aktionen */}
                    <td
                      style={{ padding: '0.75rem 1rem' }}
                      onClick={(e) => e.stopPropagation()}
                    >
                      <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <button
                          onClick={() => setEditingCompany(company)}
                          style={{
                            padding: '0.25rem 0.625rem',
                            fontSize: '0.8125rem',
                            background: 'transparent',
                            border: '1px solid var(--color-border)',
                            borderRadius: 'var(--radius-sm)',
                            cursor: 'pointer',
                            color: 'var(--color-text-secondary)',
                          }}
                        >
                          Bearbeiten
                        </button>
                        <button
                          onClick={() => setDeletingCompany(company)}
                          style={{
                            padding: '0.25rem 0.625rem',
                            fontSize: '0.8125rem',
                            background: 'transparent',
                            border: '1px solid #fecaca',
                            borderRadius: 'var(--radius-sm)',
                            cursor: 'pointer',
                            color: 'var(--color-error)',
                          }}
                        >
                          Löschen
                        </button>
                      </div>
                    </td>
                  </tr>

                  {/* Contact Sub-Rows (lazy-loaded) */}
                  {isExpanded && <ContactSubRows companyId={company.id} />}
                </Fragment>
              );
            })}
          </tbody>
        </table>

        {/* Paginierung */}
        {pagination && pagination.totalPages > 1 && (
          <div className={styles.pagination}>
            <span>
              Seite {pagination.page} von {pagination.totalPages} (
              {pagination.total} Einträge)
            </span>
            <div className={styles.paginationButtons}>
              <button
                className={styles.paginationBtn}
                disabled={pagination.page <= 1}
                onClick={() => setPage((p) => p - 1)}
              >
                Zurück
              </button>
              <button
                className={styles.paginationBtn}
                disabled={pagination.page >= pagination.totalPages}
                onClick={() => setPage((p) => p + 1)}
              >
                Weiter
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Modal: Neues Unternehmen */}
      <CompanyFormModal
        isOpen={isCreateOpen}
        onClose={() => setCreateOpen(false)}
        onSuccess={() => setCreateOpen(false)}
      />

      {/* Modal: Unternehmen bearbeiten */}
      <CompanyFormModal
        isOpen={!!editingCompany}
        onClose={() => setEditingCompany(null)}
        company={editingCompany}
        onSuccess={() => setEditingCompany(null)}
      />

      {/* Modal: Unternehmen löschen */}
      <Modal
        isOpen={!!deletingCompany}
        onClose={() => setDeletingCompany(null)}
        title="Unternehmen löschen"
        maxWidth="420px"
      >
        <p
          style={{
            fontSize: '0.9375rem',
            color: 'var(--color-text)',
            marginBottom: '0.5rem',
          }}
        >
          Soll das Unternehmen <strong>{deletingCompany?.name}</strong> wirklich
          gelöscht werden?
        </p>
        <p
          style={{
            fontSize: '0.8125rem',
            color: 'var(--color-error)',
            marginBottom: '1.5rem',
          }}
        >
          Verknüpfte Kontakte und Vorgänge verlieren die Zuordnung.
        </p>
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '0.75rem',
          }}
        >
          <button
            onClick={() => setDeletingCompany(null)}
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              cursor: 'pointer',
              color: 'var(--color-text-secondary)',
            }}
          >
            Abbrechen
          </button>
          <button
            onClick={() =>
              deletingCompany &&
              deleteMutation.mutate(deletingCompany.id, {
                onSuccess: () => setDeletingCompany(null),
              })
            }
            disabled={deleteMutation.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-error)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: deleteMutation.isPending ? 'wait' : 'pointer',
              opacity: deleteMutation.isPending ? 0.7 : 1,
            }}
          >
            {deleteMutation.isPending ? 'Löschen...' : 'Endgültig löschen'}
          </button>
        </div>
      </Modal>
    </div>
  );
}
