/**
 * 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';

export const CommcoachSettingsView: React.FC = () => {
  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('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}>Einstellungen werden geladen...</div>;
  }

  return (
    <div className={styles.settings}>
      <h2 className={styles.heading}>Coaching-Einstellungen</h2>

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

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

      <div className={styles.section}>
        <h3 className={styles.sectionTitle}>Erinnerungen</h3>
        <div className={styles.field}>
          <label className={styles.checkboxLabel}>
            <input type="checkbox" checked={reminderEnabled} onChange={e => setReminderEnabled(e.target.checked)} />
            Taegliche Coaching-Erinnerung per E-Mail
          </label>
        </div>
        {reminderEnabled && (
          <div className={styles.field}>
            <label className={styles.label}>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)} />
            Session-Zusammenfassung per E-Mail senden
          </label>
        </div>
      </div>

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

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

export default CommcoachSettingsView;
