import { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { useAppStore } from '../../store/appStore';
import styles from './ConfigScreen.module.css';

interface ValidationResult {
  file: string;
  status: 'ok' | 'warn' | 'error';
  message?: string;
}

interface Props {
  onDone?: () => void;
}

export default function ConfigScreen({ onDone }: Props) {
  const { uoRoot, servuoScripts, setUoRoot, setServuoScripts, setIsConfigured } = useAppStore();
  const [uoResults, setUoResults] = useState<ValidationResult[]>([]);
  const [scriptResults, setScriptResults] = useState<ValidationResult[]>([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function pickUoRoot() {
    const dir = await open({ directory: true, multiple: false, title: 'Select UO Client Folder' });
    if (!dir || Array.isArray(dir)) return;
    setUoRoot(dir);
    const results = await invoke<ValidationResult[]>('validate_uo_root', { path: dir });
    setUoResults(results);
  }

  async function pickScriptsPath() {
    const dir = await open({ directory: true, multiple: false, title: 'Select ServUO Scripts Folder' });
    if (!dir || Array.isArray(dir)) return;
    setServuoScripts(dir);
    const results = await invoke<ValidationResult[]>('validate_scripts_path', { path: dir });
    setScriptResults(results);
  }

  async function handleSave() {
    setSaving(true);
    setError(null);
    try {
      await invoke('set_config', { key: 'uo_root', value: uoRoot });
      await invoke('set_config', { key: 'seruo_scripts', value: servuoScripts });
      setIsConfigured(true);
      onDone?.();
    } catch (e) {
      setError(String(e));
    } finally {
      setSaving(false);
    }
  }

  const canSave =
    uoRoot &&
    servuoScripts &&
    !uoResults.some((r) => r.status === 'error') &&
    !scriptResults.some((r) => r.status === 'error');

  return (
    <div className={styles.screen}>
      <div className={styles.card}>
        <h1 className={`${styles.title} font-cinzel`}>Configuration</h1>
        <p className={styles.subtitle}>Set paths to your UO client and ServUO Scripts folder.</p>

        <div className={styles.field}>
          <label className={styles.label}>UO Client Root</label>
          <div className={styles.row}>
            <input
              type="text"
              readOnly
              value={uoRoot}
              placeholder="Not set"
              className={styles.pathInput}
            />
            <button className={styles.btn} onClick={pickUoRoot}>Browse…</button>
          </div>
          {uoResults.length > 0 && <ValidationList results={uoResults} />}
        </div>

        <div className={styles.field}>
          <label className={styles.label}>ServUO Scripts Path</label>
          <div className={styles.row}>
            <input
              type="text"
              readOnly
              value={servuoScripts}
              placeholder="Not set"
              className={styles.pathInput}
            />
            <button className={styles.btn} onClick={pickScriptsPath}>Browse…</button>
          </div>
          {scriptResults.length > 0 && <ValidationList results={scriptResults} />}
        </div>

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

        <div className={styles.actions}>
          {onDone && (
            <button className={`${styles.btn} ${styles.btnSecondary}`} onClick={onDone}>
              Cancel
            </button>
          )}
          <button
            className={`${styles.btn} ${styles.btnPrimary}`}
            onClick={handleSave}
            disabled={!canSave || saving}
          >
            {saving ? 'Saving…' : 'Save Configuration'}
          </button>
        </div>
      </div>
    </div>
  );
}

function ValidationList({ results }: { results: ValidationResult[] }) {
  return (
    <ul className={styles.validationList}>
      {results.map((r, i) => (
        <li key={i} className={styles.validationItem} data-status={r.status}>
          <span className={styles.validationIcon}>
            {r.status === 'ok' ? '✅' : r.status === 'warn' ? '⚠️' : '❌'}
          </span>
          <span className={styles.validationFile}>{r.file}</span>
          {r.message && <span className={styles.validationMsg}>{r.message}</span>}
        </li>
      ))}
    </ul>
  );
}
