/**
 * CommCoach Settings View
 *
 * Coaching-specific settings: reminders, email notifications, stats.
 * Voice/language settings are in user-level settings (/settings -> "Stimme & Sprache").
 */

import React, { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { useApiRequest } from '../../../hooks/useApi';
import { useInstanceId } from '../../../hooks/useCurrentInstance';
import {
  getProfileApi, updateProfileApi,
  type CoachingUserProfile,
} from '../../../api/commcoachApi';
import styles from './CommcoachSettingsView.module.css';

import { useLanguage } from '../../../providers/language/LanguageContext';

export const CommcoachSettingsView: React.FC = () => {
    const { t } = useLanguage();

  const { request } = useApiRequest();
  const instanceId = useInstanceId();

  const [profile, setProfile] = useState<CoachingUserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [reminderEnabled, setReminderEnabled] = useState(false);
  const [reminderTime, setReminderTime] = useState('09:00');
  const [emailEnabled, setEmailEnabled] = useState(true);

  useEffect(() => {
    if (!instanceId) return;
    const loadData = async () => {
      setLoading(true);
      try {
        const profileData = await getProfileApi(request, instanceId);
        setProfile(profileData);
        if (profileData) {
          setReminderEnabled(profileData.dailyReminderEnabled || false);
          setReminderTime(profileData.dailyReminderTime || '09:00');
          setEmailEnabled(profileData.emailSummaryEnabled !== false);
        }
      } catch (err: any) {
        setError(err.message || 'Fehler beim Laden');
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, [request, instanceId]);

  const handleSave = useCallback(async () => {
    if (!instanceId) return;
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      const updated = await updateProfileApi(request, instanceId, {
        dailyReminderEnabled: reminderEnabled,
        dailyReminderTime: reminderTime,
        emailSummaryEnabled: emailEnabled,
      });
      setProfile(updated);
      setSuccess(t('Einstellungen gespeichert'));
      setTimeout(() => setSuccess(null), 3000);
    } catch (err: any) {
      setError(err.message || 'Fehler beim Speichern');
    } finally {
      setSaving(false);
    }
  }, [request, instanceId, reminderEnabled, reminderTime, emailEnabled]);

  if (loading) {
    return <div className={styles.loading}>{t('Einstellungen werden geladen')}</div>;
  }

  return (
    <div className={styles.settings}>
      {error && <div className={styles.error}>{error}</div>}
      {success && <div className={styles.success}>{success}</div>}

      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>{t('Stimme/Sprache')}</h3>
        <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary, #888)', margin: '0 0 0.5rem' }}>
          {t('Stimme und Sprache werden zentral in den Benutzereinstellungen konfiguriert.')}
        </p>
        <Link to="/settings" onClick={() => {}} style={{ fontSize: '0.85rem', color: 'var(--primary-color, #2563eb)' }}>
          {t('Benutzereinstellungen öffnen (Tab "Stimme & Sprache")')}
        </Link>
      </div>

      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>{t('Erinnerungen')}</h3>
        <div className={styles.field}>
          <label className={styles.checkboxLabel}>
            <input type="checkbox" checked={reminderEnabled} onChange={e => setReminderEnabled(e.target.checked)} />
            {t('Tägliche Coaching-Erinnerung per E-Mail')}
          </label>
        </div>
        {reminderEnabled && (
          <div className={styles.field}>
            <label className={styles.label}>{t('Uhrzeit')}</label>
            <input type="time" className={styles.input} value={reminderTime} onChange={e => setReminderTime(e.target.value)} />
          </div>
        )}
        <div className={styles.field}>
          <label className={styles.checkboxLabel}>
            <input type="checkbox" checked={emailEnabled} onChange={e => setEmailEnabled(e.target.checked)} />
            {t('Session-Zusammenfassung per E-Mail senden')}
          </label>
        </div>
      </div>

      {profile && (
        <div className={styles.section}>
          <h3 className={styles.sectionTitle}>{t('Statistik')}</h3>
          <div className={styles.statsGrid}>
            <div className={styles.statItem}><span className={styles.statValue}>{profile.totalSessions}</span><span className={styles.statLabel}>{t('Sessions gesamt')}</span></div>
            <div className={styles.statItem}><span className={styles.statValue}>{profile.totalMinutes}</span><span className={styles.statLabel}>{t('Minuten gesamt')}</span></div>
            <div className={styles.statItem}><span className={styles.statValue}>{profile.streakDays}</span><span className={styles.statLabel}>{t('Aktueller Streak')}</span></div>
            <div className={styles.statItem}><span className={styles.statValue}>{profile.longestStreak}</span><span className={styles.statLabel}>{t('Längster Streak')}</span></div>
          </div>
        </div>
      )}

      <button className={styles.saveBtn} onClick={handleSave} disabled={saving}>
        {saving ? t('speichern') : t('Einstellungen speichern')}
      </button>
    </div>
  );
};

export default CommcoachSettingsView;
