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

interface CertificationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => Promise<void>;
  certification: ExpertCertification | null;
}

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

export function CertificationModal({ isOpen, onClose, onSave, certification }: CertificationModalProps) {
  const [title, setTitle] = useState('');
  const [issuingBody, setIssuingBody] = useState('');
  const [website, setWebsite] = useState('');
  const [issueYear, setIssueYear] = useState(currentYear);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (isOpen) {
      if (certification) {
        setTitle(certification.title);
        setIssuingBody(certification.issuingBody);
        setWebsite(certification.website ?? '');
        setIssueYear(certification.issueYear);
      } else {
        setTitle('');
        setIssuingBody('');
        setWebsite('');
        setIssueYear(currentYear);
      }
      setError('');
    }
  }, [isOpen, certification]);

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

    const payload = {
      title: title.trim(),
      issuingBody: issuingBody.trim(),
      ...(website.trim() && { website: website.trim() }),
      issueYear,
    };

    try {
      if (certification) {
        await api.patch(`/expert-profile/me/certifications/${certification.id}`, payload);
      } else {
        await api.post('/expert-profile/me/certifications', 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={certification ? 'Zertifizierung bearbeiten' : 'Zertifizierung hinzufügen'}
      maxWidth="500px"
    >
      <form onSubmit={handleSubmit} className={styles.modalForm}>
        {error && <div className={styles.error}>{error}</div>}

        <div className={styles.modalField}>
          <label>Titel *</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Welche Bezeichnung trägt Ihr Zertifikat?"
            maxLength={300}
            required
          />
        </div>

        <div className={styles.modalField}>
          <label>Zertifizierungsstelle *</label>
          <input
            type="text"
            value={issuingBody}
            onChange={(e) => setIssuingBody(e.target.value)}
            placeholder="Welche Organisation hat Ihr Zertifikat erstellt?"
            maxLength={300}
            required
          />
        </div>

        <div className={styles.modalField}>
          <label>Website der Zertifizierungsstelle</label>
          <input
            type="url"
            value={website}
            onChange={(e) => setWebsite(e.target.value)}
            placeholder="https://"
            maxLength={500}
          />
        </div>

        <div className={styles.modalField}>
          <label>Ausstellungsjahr *</label>
          <select value={issueYear} onChange={(e) => setIssueYear(Number(e.target.value))} required>
            {YEARS.map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </div>

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