import { useState, useRef } from 'react';
import { useImportPreview, useImportExecute } from '../hooks';
import type {
  ImportEntityType,
  ImportDuplicateStrategy,
  ImportPreviewResponse,
  ImportExecuteResponse,
} from '../types';

const entityTypeLabels: Record<ImportEntityType, string> = {
  PERSON: 'Kontakte',
  COMPANY: 'Unternehmen',
  DEAL: 'Vorgänge',
};

/** CRM-Felder pro Entity-Typ (Datei-Spalte → CRM-Feld) */
const crmFieldsByEntity: Record<ImportEntityType, { value: string; label: string }[]> = {
  PERSON: [
    { value: 'firstName', label: 'Vorname' },
    { value: 'lastName', label: 'Nachname' },
    { value: 'email', label: 'E-Mail' },
    { value: 'phone', label: 'Telefon' },
    { value: 'companyName', label: 'Firma' },
    { value: 'position', label: 'Position' },
    { value: 'street', label: 'Straße' },
    { value: 'city', label: 'Stadt' },
    { value: 'zipCode', label: 'PLZ' },
    { value: 'country', label: 'Land' },
    { value: 'notes', label: 'Notizen' },
  ],
  COMPANY: [
    { value: 'name', label: 'Name' },
    { value: 'street', label: 'Straße' },
    { value: 'city', label: 'Stadt' },
    { value: 'zipCode', label: 'PLZ' },
    { value: 'country', label: 'Land' },
    { value: 'websiteUrl', label: 'Website' },
    { value: 'industry', label: 'Branche' },
    { value: 'vatId', label: 'USt-IdNr.' },
    { value: 'notes', label: 'Notizen' },
  ],
  DEAL: [
    { value: 'title', label: 'Titel' },
    { value: 'value', label: 'Wert' },
    { value: 'currency', label: 'Währung' },
    { value: 'expectedCloseDate', label: 'Erw. Abschluss' },
    { value: 'notes', label: 'Notizen' },
  ],
};

const duplicateLabels: Record<ImportDuplicateStrategy, string> = {
  SKIP: 'Überspringen',
  UPDATE: 'Aktualisieren',
  MARK: 'Markieren',
};

type Step = 'upload' | 'mapping' | 'result';

export function ImportPage() {
  const [step, setStep] = useState<Step>('upload');
  const [entityType, setEntityType] = useState<ImportEntityType>('PERSON');
  const [preview, setPreview] = useState<ImportPreviewResponse | null>(null);
  const [mapping, setMapping] = useState<Record<string, string>>({});
  const [duplicateStrategy, setDuplicateStrategy] =
    useState<ImportDuplicateStrategy>('SKIP');
  const [skipFirstRow, setSkipFirstRow] = useState(true);
  const [result, setResult] = useState<ImportExecuteResponse | null>(null);

  const fileRef = useRef<HTMLInputElement>(null);
  const previewMutation = useImportPreview();
  const executeMutation = useImportExecute();

  const handleUpload = () => {
    const file = fileRef.current?.files?.[0];
    if (!file) return;
    previewMutation.mutate(
      { file, entityType },
      {
        onSuccess: (res) => {
          setPreview(res.data);
          // Auto-map columns with matching names
          const autoMap: Record<string, string> = {};
          const fields = crmFieldsByEntity[entityType];
          for (const col of res.data.columns) {
            const match = fields.find(
              (f) => f.value.toLowerCase() === col.toLowerCase() ||
                f.label.toLowerCase() === col.toLowerCase(),
            );
            if (match) autoMap[col] = match.value;
          }
          setMapping(autoMap);
          setStep('mapping');
        },
      },
    );
  };

  const handleExecute = () => {
    if (!preview) return;
    executeMutation.mutate(
      {
        importId: preview.importId,
        entityType,
        mapping,
        duplicateStrategy,
        options: { skipFirstRow },
      },
      {
        onSuccess: (res) => {
          setResult(res.data);
          setStep('result');
        },
      },
    );
  };

  const handleReset = () => {
    setStep('upload');
    setPreview(null);
    setMapping({});
    setResult(null);
    if (fileRef.current) fileRef.current.value = '';
  };

  return (
    <div>
      <h1 style={{ fontSize: '1.5rem', fontWeight: 600, marginBottom: '1.5rem' }}>
        Daten importieren
      </h1>

      {/* Step indicator */}
      <div
        style={{
          display: 'flex',
          gap: '0.5rem',
          marginBottom: '2rem',
          alignItems: 'center',
        }}
      >
        <StepBadge label="1. Hochladen" active={step === 'upload'} done={step !== 'upload'} />
        <StepDivider />
        <StepBadge label="2. Zuordnung" active={step === 'mapping'} done={step === 'result'} />
        <StepDivider />
        <StepBadge label="3. Ergebnis" active={step === 'result'} done={false} />
      </div>

      {/* Step 1: Upload */}
      {step === 'upload' && (
        <div
          style={{
            background: 'var(--color-bg-card)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-md)',
            padding: '2rem',
          }}
        >
          <div style={{ marginBottom: '1.5rem' }}>
            <label style={labelStyle}>Typ</label>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              {(Object.keys(entityTypeLabels) as ImportEntityType[]).map((t) => (
                <button
                  key={t}
                  onClick={() => setEntityType(t)}
                  style={{
                    padding: '0.5rem 1rem',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-sm)',
                    fontSize: '0.875rem',
                    cursor: 'pointer',
                    background: entityType === t ? 'var(--color-primary)' : 'var(--color-bg)',
                    color: entityType === t ? 'white' : 'var(--color-text)',
                    fontWeight: entityType === t ? 600 : 400,
                  }}
                >
                  {entityTypeLabels[t]}
                </button>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: '1.5rem' }}>
            <label style={labelStyle}>Datei (CSV, XLSX oder vCard)</label>
            <input
              ref={fileRef}
              type="file"
              accept=".csv,.xlsx,.xls,.vcf"
              style={{
                display: 'block',
                padding: '0.5rem',
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-sm)',
                fontSize: '0.875rem',
                background: 'var(--color-bg)',
                color: 'var(--color-text)',
                width: '100%',
                boxSizing: 'border-box',
              }}
            />
            <p style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)', marginTop: '0.25rem' }}>
              Max. 10 MB, max. 5.000 Zeilen
            </p>
          </div>

          <button
            onClick={handleUpload}
            disabled={previewMutation.isPending}
            style={primaryBtnStyle(previewMutation.isPending)}
          >
            {previewMutation.isPending ? 'Wird analysiert...' : 'Vorschau laden'}
          </button>

          {previewMutation.isError && (
            <p style={{ color: 'var(--color-error)', marginTop: '0.75rem', fontSize: '0.875rem' }}>
              Fehler beim Laden der Vorschau. Bitte Dateiformat prüfen.
            </p>
          )}
        </div>
      )}

      {/* Step 2: Mapping */}
      {step === 'mapping' && preview && (
        <div
          style={{
            background: 'var(--color-bg-card)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-md)',
            padding: '2rem',
          }}
        >
          <p style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)', marginBottom: '1rem' }}>
            {preview.totalRows} Zeilen erkannt ({preview.format.toUpperCase()}).
            Ordne die Spalten den CRM-Feldern zu.
          </p>

          {/* Column mapping */}
          <div style={{ marginBottom: '1.5rem' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.875rem' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--color-border)' }}>
                  <th style={thStyle}>Datei-Spalte</th>
                  <th style={thStyle}>CRM-Feld</th>
                  <th style={thStyle}>Vorschau</th>
                </tr>
              </thead>
              <tbody>
                {preview.columns.map((col) => (
                  <tr key={col} style={{ borderBottom: '1px solid var(--color-border)' }}>
                    <td style={tdStyle}>{col}</td>
                    <td style={tdStyle}>
                      <select
                        value={mapping[col] ?? ''}
                        onChange={(e) =>
                          setMapping((prev) => ({
                            ...prev,
                            [col]: e.target.value,
                          }))
                        }
                        style={{
                          padding: '0.375rem 0.5rem',
                          border: '1px solid var(--color-border)',
                          borderRadius: 'var(--radius-sm)',
                          fontSize: '0.8125rem',
                          background: 'var(--color-bg)',
                          color: 'var(--color-text)',
                          width: '100%',
                        }}
                      >
                        <option value="">— ignorieren —</option>
                        {crmFieldsByEntity[entityType].map((f) => (
                          <option key={f.value} value={f.value}>
                            {f.label}
                          </option>
                        ))}
                      </select>
                    </td>
                    <td
                      style={{
                        ...tdStyle,
                        color: 'var(--color-text-muted)',
                        fontSize: '0.8125rem',
                        maxWidth: '200px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}
                    >
                      {preview.rows[0]?.[col] ?? '—'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Options */}
          <div
            style={{
              display: 'flex',
              gap: '2rem',
              alignItems: 'center',
              marginBottom: '1.5rem',
              flexWrap: 'wrap',
            }}
          >
            <div>
              <label style={labelStyle}>Duplikate</label>
              <select
                value={duplicateStrategy}
                onChange={(e) =>
                  setDuplicateStrategy(e.target.value as ImportDuplicateStrategy)
                }
                style={{
                  padding: '0.5rem 0.75rem',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.875rem',
                  background: 'var(--color-bg)',
                  color: 'var(--color-text)',
                }}
              >
                {(Object.keys(duplicateLabels) as ImportDuplicateStrategy[]).map(
                  (s) => (
                    <option key={s} value={s}>
                      {duplicateLabels[s]}
                    </option>
                  ),
                )}
              </select>
            </div>

            <label
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '0.375rem',
                fontSize: '0.875rem',
                color: 'var(--color-text)',
                cursor: 'pointer',
                paddingTop: '1.25rem',
              }}
            >
              <input
                type="checkbox"
                checked={skipFirstRow}
                onChange={(e) => setSkipFirstRow(e.target.checked)}
              />
              Erste Zeile ist Kopfzeile
            </label>
          </div>

          <div style={{ display: 'flex', gap: '0.75rem' }}>
            <button
              onClick={handleExecute}
              disabled={
                executeMutation.isPending ||
                Object.values(mapping).filter(Boolean).length === 0
              }
              style={primaryBtnStyle(
                executeMutation.isPending ||
                  Object.values(mapping).filter(Boolean).length === 0,
              )}
            >
              {executeMutation.isPending
                ? 'Wird importiert...'
                : `${preview.totalRows} Einträge importieren`}
            </button>
            <button onClick={handleReset} style={secondaryBtnStyle}>
              Abbrechen
            </button>
          </div>

          {executeMutation.isError && (
            <p style={{ color: 'var(--color-error)', marginTop: '0.75rem', fontSize: '0.875rem' }}>
              Fehler beim Import. Bitte versuche es erneut.
            </p>
          )}
        </div>
      )}

      {/* Step 3: Result */}
      {step === 'result' && result && (
        <div
          style={{
            background: 'var(--color-bg-card)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-md)',
            padding: '2rem',
          }}
        >
          <h2
            style={{
              fontSize: '1.125rem',
              fontWeight: 600,
              marginBottom: '1rem',
              color:
                result.errors > 0 ? 'var(--color-warning, #d97706)' : 'var(--color-success, #16a34a)',
            }}
          >
            {result.errors > 0 ? 'Import mit Warnungen abgeschlossen' : 'Import erfolgreich'}
          </h2>

          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
              gap: '1rem',
              marginBottom: '1.5rem',
            }}
          >
            <ResultCard label="Erstellt" value={result.created} color="var(--color-success, #16a34a)" />
            <ResultCard label="Aktualisiert" value={result.updated} color="var(--color-primary)" />
            <ResultCard label="Übersprungen" value={result.skipped} color="var(--color-text-muted)" />
            <ResultCard label="Fehler" value={result.errors} color="var(--color-error)" />
          </div>

          {result.errorDetails.length > 0 && (
            <div style={{ marginBottom: '1.5rem' }}>
              <h3
                style={{
                  fontSize: '0.875rem',
                  fontWeight: 600,
                  marginBottom: '0.5rem',
                }}
              >
                Fehlerdetails
              </h3>
              <div
                style={{
                  maxHeight: '200px',
                  overflow: 'auto',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.8125rem',
                }}
              >
                {result.errorDetails.map((err, i) => (
                  <div
                    key={i}
                    style={{
                      padding: '0.5rem 0.75rem',
                      borderBottom: '1px solid var(--color-border)',
                      color: 'var(--color-error)',
                    }}
                  >
                    Zeile {err.row}: {err.field} — {err.message}
                  </div>
                ))}
              </div>
            </div>
          )}

          <button onClick={handleReset} style={primaryBtnStyle(false)}>
            Neuer Import
          </button>
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

const labelStyle: React.CSSProperties = {
  fontSize: '0.8125rem',
  fontWeight: 500,
  color: 'var(--color-text-muted)',
  display: 'block',
  marginBottom: '0.375rem',
};

const thStyle: React.CSSProperties = {
  padding: '0.625rem 0.75rem',
  textAlign: 'left',
  fontWeight: 600,
  fontSize: '0.8125rem',
  color: 'var(--color-text-muted)',
};

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

function primaryBtnStyle(disabled: boolean): React.CSSProperties {
  return {
    padding: '0.625rem 1.25rem',
    background: 'var(--color-primary)',
    color: 'white',
    border: 'none',
    borderRadius: 'var(--radius-sm)',
    fontSize: '0.875rem',
    fontWeight: 600,
    cursor: disabled ? 'not-allowed' : 'pointer',
    opacity: disabled ? 0.5 : 1,
  };
}

const secondaryBtnStyle: React.CSSProperties = {
  padding: '0.625rem 1rem',
  background: 'transparent',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.875rem',
  cursor: 'pointer',
  color: 'var(--color-text-secondary)',
};

function StepBadge({
  label,
  active,
  done,
}: {
  label: string;
  active: boolean;
  done: boolean;
}) {
  return (
    <span
      style={{
        padding: '0.375rem 0.75rem',
        borderRadius: '9999px',
        fontSize: '0.8125rem',
        fontWeight: active ? 600 : 400,
        background: active
          ? 'var(--color-primary)'
          : done
            ? '#dbeafe'
            : 'var(--color-bg)',
        color: active ? 'white' : done ? '#1e40af' : 'var(--color-text-muted)',
        border: active || done ? 'none' : '1px solid var(--color-border)',
      }}
    >
      {label}
    </span>
  );
}

function StepDivider() {
  return (
    <span
      style={{
        width: '2rem',
        height: '1px',
        background: 'var(--color-border)',
        display: 'inline-block',
      }}
    />
  );
}

function ResultCard({
  label,
  value,
  color,
}: {
  label: string;
  value: number;
  color: string;
}) {
  return (
    <div
      style={{
        textAlign: 'center',
        padding: '1rem',
        background: 'var(--color-bg)',
        borderRadius: 'var(--radius-sm)',
        border: '1px solid var(--color-border)',
      }}
    >
      <div style={{ fontSize: '1.5rem', fontWeight: 700, color }}>{value}</div>
      <div
        style={{
          fontSize: '0.75rem',
          color: 'var(--color-text-muted)',
          marginTop: '0.25rem',
        }}
      >
        {label}
      </div>
    </div>
  );
}
