import { useState, useEffect } from 'react';
import { Modal } from '../../components/Modal';
import { useCreateActivity, useUpdateActivity } from '../hooks';
import type { Activity, ActivityType } from '../types';

interface ActivityFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  contactId?: string;
  companyId?: string;
  activity?: Activity | null;
  onSuccess: () => void;
}

const ACTIVITY_TYPE_LABELS: Record<ActivityType, string> = {
  NOTE: 'Notiz',
  CALL: 'Anruf',
  EMAIL: 'E-Mail',
  MEETING: 'Meeting',
  TASK: 'Aufgabe',
  FOLLOWUP: 'Follow-Up',
};

const ACTIVITY_TYPES: ActivityType[] = [
  'NOTE',
  'CALL',
  'EMAIL',
  'MEETING',
  'TASK',
];

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

const inputStyle: 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)',
};

export function ActivityFormModal({
  isOpen,
  onClose,
  contactId,
  companyId,
  activity,
  onSuccess,
}: ActivityFormModalProps) {
  const isEditMode = !!activity;
  const createMutation = useCreateActivity();
  const updateMutation = useUpdateActivity();
  const mutation = isEditMode ? updateMutation : createMutation;

  const [error, setError] = useState('');
  const [type, setType] = useState<ActivityType>('NOTE');
  const [subject, setSubject] = useState('');
  const [description, setDescription] = useState('');
  const [scheduledAt, setScheduledAt] = useState('');
  const [completedAt, setCompletedAt] = useState('');

  useEffect(() => {
    if (isOpen) {
      setError('');
      if (activity) {
        setType(activity.type);
        setSubject(activity.subject);
        setDescription(activity.description ?? '');
        setScheduledAt(
          activity.scheduledAt
            ? activity.scheduledAt.slice(0, 16)
            : '',
        );
        setCompletedAt(
          activity.completedAt
            ? activity.completedAt.slice(0, 16)
            : '',
        );
      } else {
        setType('NOTE');
        setSubject('');
        setDescription('');
        setScheduledAt('');
        setCompletedAt('');
      }
    }
  }, [isOpen, activity]);

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

    if (!subject.trim()) {
      setError('Betreff ist ein Pflichtfeld');
      return;
    }

    if (isEditMode && activity) {
      updateMutation.mutate(
        {
          id: activity.id,
          data: {
            type,
            subject: subject.trim(),
            ...(description ? { description } : {}),
            ...(scheduledAt ? { scheduledAt: new Date(scheduledAt).toISOString() } : {}),
            ...(completedAt ? { completedAt: new Date(completedAt).toISOString() } : {}),
          },
        },
        {
          onSuccess: () => onSuccess(),
          onError: (err: unknown) => {
            const msg =
              (err as { response?: { data?: { error?: { message?: string } } } })
                ?.response?.data?.error?.message ?? 'Fehler beim Speichern';
            setError(msg);
          },
        },
      );
    } else {
      createMutation.mutate(
        {
          ...(contactId ? { contactId } : {}),
          ...(companyId ? { companyId } : {}),
          type,
          subject: subject.trim(),
          ...(description ? { description } : {}),
          ...(scheduledAt ? { scheduledAt: new Date(scheduledAt).toISOString() } : {}),
          ...(completedAt ? { completedAt: new Date(completedAt).toISOString() } : {}),
        },
        {
          onSuccess: () => onSuccess(),
          onError: (err: unknown) => {
            const msg =
              (err as { response?: { data?: { error?: { message?: string } } } })
                ?.response?.data?.error?.message ?? 'Fehler beim Anlegen';
            setError(msg);
          },
        },
      );
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={isEditMode ? 'Aktivität bearbeiten' : 'Neue Aktivität'}
      maxWidth="500px"
    >
      <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>
        )}

        {/* Typ */}
        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Typ</label>
          <select
            value={type}
            onChange={(e) => setType(e.target.value as ActivityType)}
            style={{ ...inputStyle, cursor: 'pointer' }}
          >
            {ACTIVITY_TYPES.map((t) => (
              <option key={t} value={t}>
                {ACTIVITY_TYPE_LABELS[t]}
              </option>
            ))}
          </select>
        </div>

        {/* Betreff */}
        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Betreff *</label>
          <input
            style={inputStyle}
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            placeholder="Betreff der Aktivität"
            required
          />
        </div>

        {/* Beschreibung */}
        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Beschreibung</label>
          <textarea
            style={{ ...inputStyle, minHeight: 80, resize: 'vertical' }}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Optionale Beschreibung..."
          />
        </div>

        {/* Geplant am / Erledigt am */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: '0.75rem',
            marginBottom: '1.5rem',
          }}
        >
          <div>
            <label style={labelStyle}>Geplant am</label>
            <input
              type="datetime-local"
              style={inputStyle}
              value={scheduledAt}
              onChange={(e) => setScheduledAt(e.target.value)}
            />
          </div>
          <div>
            <label style={labelStyle}>Erledigt am</label>
            <input
              type="datetime-local"
              style={inputStyle}
              value={completedAt}
              onChange={(e) => setCompletedAt(e.target.value)}
            />
          </div>
        </div>

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