import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
import {
  useCompanyRelationships,
  useCreateCompanyRelationship,
  useDeleteCompanyRelationship,
  useRelationshipTypes,
  useCompanies,
} from '../hooks';
import type { CompanyRelationship } from '../types';
import styles from './CompanyDetailPage.module.css';

// ============================================================
//  Props
// ============================================================

interface CompanyRelationshipsCardProps {
  companyId: string;
}

// ============================================================
//  Component
// ============================================================

export function CompanyRelationshipsCard({ companyId }: CompanyRelationshipsCardProps) {
  const navigate = useNavigate();
  const { data, isLoading } = useCompanyRelationships(companyId);
  const deleteMut = useDeleteCompanyRelationship();

  const [isAddOpen, setAddOpen] = useState(false);

  const relationships: CompanyRelationship[] = data?.data ?? [];

  const handleDelete = (relId: string) => {
    if (window.confirm('Beziehung wirklich entfernen?')) {
      deleteMut.mutate({ companyId, relationshipId: relId });
    }
  };

  return (
    <div className={styles.card}>
      <div className={styles.cardTitleRow}>
        <h2 className={styles.cardTitle} style={{ marginBottom: 0 }}>
          Beziehungen ({relationships.length})
        </h2>
        <button className={styles.smallAddBtn} onClick={() => setAddOpen(true)}>
          + Neu
        </button>
      </div>

      {isLoading ? (
        <p style={{ color: 'var(--color-text-muted)', fontSize: '0.8125rem' }}>
          Laden...
        </p>
      ) : relationships.length === 0 ? (
        <p style={{ color: 'var(--color-text-muted)', fontSize: '0.8125rem' }}>
          Keine Beziehungen vorhanden
        </p>
      ) : (
        <div>
          {relationships.map((rel) => (
            <div key={rel.id} className={styles.relationItem}>
              <div className={styles.relationInfo}>
                <span
                  className={styles.relationName}
                  onClick={() =>
                    navigate(`/crm/companies/${rel.relatedCompany.id}`)
                  }
                >
                  {rel.relatedCompany.name}
                </span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.375rem' }}>
                  <span className={styles.relationTypeBadge}>
                    {rel.relationshipType.name}
                  </span>
                  {rel.direction === 'incoming' && (
                    <span
                      style={{
                        fontSize: '0.6875rem',
                        color: 'var(--color-text-muted)',
                      }}
                    >
                      (eingehend)
                    </span>
                  )}
                </div>
              </div>
              <button
                className={styles.relationDeleteBtn}
                onClick={() => handleDelete(rel.id)}
                title="Entfernen"
              >
                <svg
                  width="12"
                  height="12"
                  viewBox="0 0 12 12"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                >
                  <path d="M3 3l6 6M9 3l-6 6" />
                </svg>
              </button>
            </div>
          ))}
        </div>
      )}

      {/* Add Modal */}
      <AddRelationshipModal
        isOpen={isAddOpen}
        onClose={() => setAddOpen(false)}
        companyId={companyId}
      />
    </div>
  );
}

// ============================================================
//  Add Relationship Modal
// ============================================================

interface AddRelationshipModalProps {
  isOpen: boolean;
  onClose: () => void;
  companyId: string;
}

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

const selectStyle: React.CSSProperties = {
  width: '100%',
  padding: '0.625rem 0.75rem',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.9375rem',
  outline: 'none',
  boxSizing: 'border-box',
  background: 'var(--color-bg-card)',
  color: 'var(--color-text)',
  cursor: 'pointer',
};

function AddRelationshipModal({ isOpen, onClose, companyId }: AddRelationshipModalProps) {
  const createMut = useCreateCompanyRelationship();
  const { data: typesData } = useRelationshipTypes();
  const { data: companiesData } = useCompanies({ page: 1, pageSize: 200 });

  const types = typesData?.data ?? [];
  const companies = (companiesData?.data ?? []).filter((c) => c.id !== companyId);

  const [relatedCompanyId, setRelatedCompanyId] = useState('');
  const [relationshipTypeId, setRelationshipTypeId] = useState('');
  const [notes, setNotes] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!relatedCompanyId || !relationshipTypeId) {
      setError('Bitte wähle ein Unternehmen und einen Beziehungstyp.');
      return;
    }

    createMut.mutate(
      {
        companyId,
        data: {
          relatedCompanyId,
          relationshipTypeId,
          ...(notes.trim() ? { notes: notes.trim() } : {}),
        },
      },
      {
        onSuccess: () => {
          setRelatedCompanyId('');
          setRelationshipTypeId('');
          setNotes('');
          onClose();
        },
        onError: (err: unknown) => {
          const msg =
            (err as { response?: { data?: { error?: { message?: string } } } })
              ?.response?.data?.error?.message ?? 'Fehler beim Erstellen';
          setError(msg);
        },
      },
    );
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Beziehung hinzufügen"
      maxWidth="460px"
    >
      <form onSubmit={handleSubmit}>
        {error && (
          <div
            style={{
              padding: '0.75rem',
              background: '#fef2f2',
              border: '1px solid #fecaca',
              borderRadius: 'var(--radius-sm)',
              color: 'var(--color-error)',
              fontSize: '0.875rem',
              marginBottom: '1rem',
            }}
          >
            {error}
          </div>
        )}

        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Unternehmen *</label>
          <select
            style={selectStyle}
            value={relatedCompanyId}
            onChange={(e) => setRelatedCompanyId(e.target.value)}
            required
          >
            <option value="">— Unternehmen wählen —</option>
            {companies.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Beziehungstyp *</label>
          <select
            style={selectStyle}
            value={relationshipTypeId}
            onChange={(e) => setRelationshipTypeId(e.target.value)}
            required
          >
            <option value="">— Typ wählen —</option>
            {types.map((t) => (
              <option key={t.id} value={t.id}>
                {t.name}
              </option>
            ))}
          </select>
        </div>

        <div style={{ marginBottom: '1.5rem' }}>
          <label style={labelStyle}>Notizen</label>
          <textarea
            style={{
              ...selectStyle,
              cursor: 'text',
              minHeight: 60,
              resize: 'vertical',
            }}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Optionale Notizen..."
          />
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
          <button
            type="button"
            onClick={onClose}
            disabled={createMut.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
            type="submit"
            disabled={createMut.isPending}
            style={{
              padding: '0.5rem 1rem',
              background: 'var(--color-primary)',
              color: 'white',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.875rem',
              fontWeight: 600,
              cursor: createMut.isPending ? 'wait' : 'pointer',
              opacity: createMut.isPending ? 0.7 : 1,
            }}
          >
            {createMut.isPending ? 'Erstellen...' : 'Erstellen'}
          </button>
        </div>
      </form>
    </Modal>
  );
}
