import { useState, useEffect, type FormEvent } from 'react';
import { Modal } from '../../components/Modal';
import api from '../../api/client';
import type { ExpertProject } from '../ExpertProfileTab';
import styles from '../ExpertProfileTab.module.css';

interface ProjectModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => Promise<void>;
  project: ExpertProject | null;
}

const MONTHS = [
  { value: 1, label: 'Januar' }, { value: 2, label: 'Februar' },
  { value: 3, label: 'März' }, { value: 4, label: 'April' },
  { value: 5, label: 'Mai' }, { value: 6, label: 'Juni' },
  { value: 7, label: 'Juli' }, { value: 8, label: 'August' },
  { value: 9, label: 'September' }, { value: 10, label: 'Oktober' },
  { value: 11, label: 'November' }, { value: 12, label: 'Dezember' },
];

const COMPANY_SIZES = ['1-10', '11-50', '51-200', '201-500', '501-1000', '1001-5000', '5000+'];

const INDUSTRIES = [
  'IT-Dienstleistung', 'Software-Entwicklung', 'Cloud & Hosting', 'Telekommunikation',
  'Finanzdienstleistung', 'Versicherung', 'Gesundheitswesen', 'Pharma & Medizintechnik',
  'Automobilindustrie', 'Maschinenbau', 'Energiewirtschaft', 'Logistik & Transport',
  'Handel & E-Commerce', 'Medien & Unterhaltung', 'Bildung & Forschung',
  'Öffentlicher Sektor', 'Beratung & Consulting', 'Luft- und Raumfahrt',
  'Chemie & Werkstoffe', 'Sonstige',
];

const currentYear = new Date().getFullYear();
const YEARS = Array.from({ length: 40 }, (_, i) => currentYear - i);

export function ProjectModal({ isOpen, onClose, onSave, project }: ProjectModalProps) {
  const [fromMonth, setFromMonth] = useState(1);
  const [fromYear, setFromYear] = useState(currentYear);
  const [toMonth, setToMonth] = useState(1);
  const [toYear, setToYear] = useState(currentYear);
  const [isCurrent, setIsCurrent] = useState(false);
  const [role, setRole] = useState('');
  const [tasks, setTasks] = useState('');
  const [company, setCompany] = useState('');
  const [companySize, setCompanySize] = useState('');
  const [industry, setIndustry] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (isOpen) {
      if (project) {
        setFromMonth(project.fromMonth);
        setFromYear(project.fromYear);
        setToMonth(project.toMonth ?? 1);
        setToYear(project.toYear ?? currentYear);
        setIsCurrent(project.isCurrent);
        setRole(project.role);
        setTasks(project.tasks ?? '');
        setCompany(project.company ?? '');
        setCompanySize(project.companySize ?? '');
        setIndustry(project.industry ?? '');
      } else {
        setFromMonth(1);
        setFromYear(currentYear);
        setToMonth(1);
        setToYear(currentYear);
        setIsCurrent(false);
        setRole('');
        setTasks('');
        setCompany('');
        setCompanySize('');
        setIndustry('');
      }
      setError('');
    }
  }, [isOpen, project]);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    const payload = {
      fromMonth,
      fromYear,
      ...(!isCurrent && { toMonth, toYear }),
      isCurrent,
      role: role.trim(),
      ...(tasks.trim() && { tasks: tasks.trim() }),
      ...(company.trim() && { company: company.trim() }),
      ...(companySize && { companySize }),
      ...(industry && { industry }),
    };

    try {
      if (project) {
        await api.patch(`/expert-profile/me/projects/${project.id}`, payload);
      } else {
        await api.post('/expert-profile/me/projects', payload);
      }
      await onSave();
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { message?: string } } };
      setError(apiErr.response?.data?.message ?? 'Fehler beim Speichern');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={project ? 'Projekt bearbeiten' : 'Neues Projekt hinzufügen'}
      maxWidth="650px"
    >
      <form onSubmit={handleSubmit} className={styles.modalForm}>
        {error && <div className={styles.error}>{error}</div>}

        {/* Zeitraum von */}
        <div className={styles.modalFieldRow}>
          <div className={styles.modalField}>
            <label>Zeitraum von *</label>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <select value={fromMonth} onChange={(e) => setFromMonth(Number(e.target.value))} required>
                {MONTHS.map((m) => (
                  <option key={m.value} value={m.value}>{m.label}</option>
                ))}
              </select>
              <select value={fromYear} onChange={(e) => setFromYear(Number(e.target.value))} required>
                {YEARS.map((y) => (
                  <option key={y} value={y}>{y}</option>
                ))}
              </select>
            </div>
          </div>
          <div className={styles.modalField}>
            <label>Zeitraum bis *</label>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <select
                value={toMonth}
                onChange={(e) => setToMonth(Number(e.target.value))}
                disabled={isCurrent}
              >
                {MONTHS.map((m) => (
                  <option key={m.value} value={m.value}>{m.label}</option>
                ))}
              </select>
              <select
                value={toYear}
                onChange={(e) => setToYear(Number(e.target.value))}
                disabled={isCurrent}
              >
                {YEARS.map((y) => (
                  <option key={y} value={y}>{y}</option>
                ))}
              </select>
            </div>
          </div>
        </div>

        <div className={styles.checkboxRow}>
          <input
            type="checkbox"
            id="isCurrent"
            checked={isCurrent}
            onChange={(e) => setIsCurrent(e.target.checked)}
          />
          <label htmlFor="isCurrent">bis heute</label>
        </div>

        <div className={styles.modalField}>
          <label>Tätigkeit *</label>
          <input
            type="text"
            value={role}
            onChange={(e) => setRole(e.target.value)}
            placeholder="z.B. Senior DevOps Engineer"
            maxLength={200}
            required
          />
        </div>

        <div className={styles.modalField}>
          <label>Aufgaben</label>
          <textarea
            value={tasks}
            onChange={(e) => setTasks(e.target.value)}
            placeholder="Beschreiben Sie Ihre Aufgaben..."
            maxLength={1500}
            rows={4}
          />
          <div className={`${styles.charCount} ${tasks.length > 1400 ? styles.charCountWarn : ''}`}>
            {tasks.length}/1.500
          </div>
        </div>

        <div className={styles.modalField}>
          <label>Firma</label>
          <input
            type="text"
            value={company}
            onChange={(e) => setCompany(e.target.value)}
            placeholder="Firmenname"
            maxLength={200}
          />
        </div>

        <div className={styles.modalFieldRow}>
          <div className={styles.modalField}>
            <label>Unternehmensgröße</label>
            <select value={companySize} onChange={(e) => setCompanySize(e.target.value)}>
              <option value="">Anzahl der Mitarbeitenden</option>
              {COMPANY_SIZES.map((s) => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>
          <div className={styles.modalField}>
            <label>Branche</label>
            <select value={industry} onChange={(e) => setIndustry(e.target.value)}>
              <option value="">Bitte wählen</option>
              {INDUSTRIES.map((ind) => (
                <option key={ind} value={ind}>{ind}</option>
              ))}
            </select>
          </div>
        </div>

        <div className={styles.btnRow}>
          <button type="button" className={styles.btnSecondary} onClick={onClose}>
            Abbrechen
          </button>
          <button type="submit" className={styles.btnPrimary} disabled={loading || !role.trim()}>
            {loading ? 'Speichern...' : project ? 'Projekt speichern' : 'Projekt hinzufügen'}
          </button>
        </div>
      </form>
    </Modal>
  );
}
