import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
import { useDeals, useDeleteDeal, usePipelines } from '../hooks';
import { DealFormModal } from './DealFormModal';
import { ProjectRequestFormModal } from './ProjectRequestFormModal';
import type { Deal, DealStatus, DealsQueryParams } from '../types';
import styles from './DealsPage.module.css';

const STATUS_COLORS: Record<DealStatus, { bg: string; color: string }> = {
  OPEN: { bg: '#dbeafe', color: '#1e40af' },
  WON: { bg: '#d1fae5', color: '#065f46' },
  LOST: { bg: '#fee2e2', color: '#991b1b' },
};

const STATUS_LABELS: Record<DealStatus, string> = {
  OPEN: 'Offen',
  WON: 'Gewonnen',
  LOST: 'Verloren',
};

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

const currencyFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
});

function dealContactName(deal: Deal): string {
  if (!deal.contact) return '—';
  const { firstName, lastName, companyName } = deal.contact;
  if (companyName) return companyName;
  return [firstName, lastName].filter(Boolean).join(' ') || '—';
}

export function DealsPage() {
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<DealStatus | ''>('');
  const [pipelineFilter, setPipelineFilter] = useState('');
  const [stageFilter, setStageFilter] = useState('');
  const [isCreateOpen, setCreateOpen] = useState(false);
  const [isProjectRequestOpen, setProjectRequestOpen] = useState(false);
  const [editingDeal, setEditingDeal] = useState<Deal | null>(null);
  const [deletingDeal, setDeletingDeal] = useState<Deal | null>(null);

  const { data: pipelinesData } = usePipelines();
  const pipelines = pipelinesData?.data ?? [];

  // Stages der gewaehlten Pipeline
  const selectedPipeline = pipelines.find((p) => p.id === pipelineFilter);
  const stages = selectedPipeline?.stages ?? [];

  // Reset stageFilter wenn Pipeline wechselt
  useEffect(() => {
    setStageFilter('');
    setPage(1);
  }, [pipelineFilter]);

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

  const params: DealsQueryParams = {
    page,
    pageSize: 25,
    ...(search ? { search } : {}),
    ...(statusFilter ? { status: statusFilter } : {}),
    ...(pipelineFilter ? { pipelineId: pipelineFilter } : {}),
    ...(stageFilter ? { stageId: stageFilter } : {}),
    sort: 'createdAt',
    order: 'desc',
  };

  const { data, isLoading, error } = useDeals(params);
  const deleteMutation = useDeleteDeal();

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

  const deals = 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 }}>Vorgänge</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <span
            style={{
              color: 'var(--color-text-muted)',
              fontSize: '0.875rem',
            }}
          >
            {pagination?.total ?? 0} Vorgänge gesamt
          </span>
          <button
            onClick={() => setProjectRequestOpen(true)}
            style={{
              padding: '0.5rem 1rem',
              background: 'transparent',
              color: 'var(--color-primary)',
              border: '1px solid var(--color-primary)',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: 'pointer',
            }}
          >
            + Neue Projektanfrage
          </button>
          <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',
            }}
          >
            + Neuer Vorgang
          </button>
        </div>
      </div>

      {/* Filterleiste */}
      <div className={styles.filterBar}>
        <input
          type="search"
          placeholder="Suche nach Titel..."
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          className={styles.searchInput}
        />
        <select
          value={pipelineFilter}
          onChange={(e) => setPipelineFilter(e.target.value)}
          className={styles.filterSelect}
        >
          <option value="">Alle Pipelines</option>
          {pipelines.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </select>
        {stages.length > 0 && (
          <select
            value={stageFilter}
            onChange={(e) => {
              setStageFilter(e.target.value);
              setPage(1);
            }}
            className={styles.filterSelect}
          >
            <option value="">Alle Stufen</option>
            {stages
              .sort((a, b) => a.sortOrder - b.sortOrder)
              .map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
          </select>
        )}
        <select
          value={statusFilter}
          onChange={(e) => {
            setStatusFilter(e.target.value as DealStatus | '');
            setPage(1);
          }}
          className={styles.filterSelect}
        >
          <option value="">Alle Status</option>
          <option value="OPEN">Offen</option>
          <option value="WON">Gewonnen</option>
          <option value="LOST">Verloren</option>
        </select>
      </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}>Titel</th>
              <th style={thStyle}>Kontakt</th>
              <th style={thStyle}>Unternehmen</th>
              <th style={thStyle}>Pipeline</th>
              <th style={{ ...thStyle, minWidth: 120 }}>Stage</th>
              <th style={{ ...thStyle, textAlign: 'right', minWidth: 100 }}>Wert</th>
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {deals.length === 0 && (
              <tr>
                <td
                  colSpan={8}
                  style={{
                    padding: '2rem',
                    textAlign: 'center',
                    color: 'var(--color-text-muted)',
                  }}
                >
                  Keine Vorgänge gefunden
                </td>
              </tr>
            )}
            {deals.map((deal) => {
              const statusStyle = STATUS_COLORS[deal.status];
              return (
                <tr
                  key={deal.id}
                  style={{
                    borderBottom: '1px solid var(--color-border)',
                    cursor: 'pointer',
                  }}
                  onClick={() => navigate(`/crm/deals/${deal.id}`)}
                >
                  <td
                    style={{
                      padding: '0.75rem 1rem',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                    }}
                  >
                    {deal.title}
                  </td>
                  <td
                    style={{
                      padding: '0.75rem 1rem',
                      fontSize: '0.875rem',
                      color: 'var(--color-text-secondary)',
                    }}
                  >
                    {dealContactName(deal)}
                  </td>
                  <td
                    style={{
                      padding: '0.75rem 1rem',
                      fontSize: '0.875rem',
                      color: 'var(--color-text-secondary)',
                    }}
                    onClick={(e) => {
                      if (deal.company) e.stopPropagation();
                    }}
                  >
                    {deal.company ? (
                      <a
                        href={`/crm/companies/${deal.company.id}`}
                        onClick={(e) => {
                          e.preventDefault();
                          navigate(`/crm/companies/${deal.company!.id}`);
                        }}
                        style={{ color: 'var(--color-primary)' }}
                      >
                        {deal.company.name}
                      </a>
                    ) : (
                      '—'
                    )}
                  </td>
                  <td
                    style={{
                      padding: '0.75rem 1rem',
                      fontSize: '0.875rem',
                      color: 'var(--color-text-secondary)',
                    }}
                  >
                    {deal.pipeline?.name ?? '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    {deal.stage && (
                      <span
                        style={{
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '0.375rem',
                          fontSize: '0.8125rem',
                        }}
                      >
                        <span
                          style={{
                            width: 8,
                            height: 8,
                            borderRadius: '50%',
                            background: deal.stage.color,
                            display: 'inline-block',
                          }}
                        />
                        {deal.stage.name}
                      </span>
                    )}
                  </td>
                  <td
                    style={{
                      padding: '0.75rem 1rem',
                      textAlign: 'right',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                    }}
                  >
                    {deal.value
                      ? currencyFormatter.format(parseFloat(deal.value))
                      : '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span
                      style={{
                        display: 'inline-block',
                        padding: '0.125rem 0.5rem',
                        borderRadius: '9999px',
                        fontSize: '0.75rem',
                        fontWeight: 500,
                        background: statusStyle.bg,
                        color: statusStyle.color,
                      }}
                    >
                      {STATUS_LABELS[deal.status]}
                    </span>
                  </td>
                  <td
                    style={{ padding: '0.75rem 1rem' }}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      <button
                        onClick={() => setEditingDeal(deal)}
                        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={() => setDeletingDeal(deal)}
                        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>
              );
            })}
          </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: Neue Projektanfrage */}
      <ProjectRequestFormModal
        isOpen={isProjectRequestOpen}
        onClose={() => setProjectRequestOpen(false)}
        onSuccess={() => { setProjectRequestOpen(false); }}
      />

      {/* Modal: Neuen Vorgang anlegen */}
      <DealFormModal
        isOpen={isCreateOpen}
        onClose={() => setCreateOpen(false)}
        onSuccess={() => setCreateOpen(false)}
      />

      {/* Modal: Vorgang bearbeiten */}
      <DealFormModal
        isOpen={!!editingDeal}
        onClose={() => setEditingDeal(null)}
        deal={editingDeal}
        onSuccess={() => setEditingDeal(null)}
      />

      {/* Modal: Vorgang löschen */}
      <Modal
        isOpen={!!deletingDeal}
        onClose={() => setDeletingDeal(null)}
        title="Vorgang löschen"
        maxWidth="420px"
      >
        <p
          style={{
            fontSize: '0.9375rem',
            color: 'var(--color-text)',
            marginBottom: '1.5rem',
          }}
        >
          Soll der Vorgang <strong>{deletingDeal?.title}</strong> wirklich gelöscht
          werden?
        </p>
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '0.75rem',
          }}
        >
          <button
            onClick={() => setDeletingDeal(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={() =>
              deletingDeal &&
              deleteMutation.mutate(deletingDeal.id, {
                onSuccess: () => setDeletingDeal(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>
  );
}
