'use client';
import { useState, useEffect, useRef } from 'react';
import { useUser } from '../layout';
import { authFetch } from '@/lib/auth-client';

export default function SettingsPage() {
  const user = useUser();

  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState(null);

  // Company info
  const [companyName, setCompanyName] = useState('');
  const [companyLogo, setCompanyLogo] = useState('');
  const [logoPreview, setLogoPreview] = useState('');
  const [savingCompany, setSavingCompany] = useState(false);
  const logoInputRef = useRef(null);

  // Profit config
  const [profitPercentage, setProfitPercentage] = useState('');
  const [savingProfit, setSavingProfit] = useState(false);

  // Historical Import
  const [importFile, setImportFile] = useState(null);
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState(null);
  const importInputRef = useRef(null);

  const showToast = (message, type = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  // Fetch config
  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const res = await authFetch('/api/config');
        const data = await res.json();
        const config = data.config || data;
        setCompanyName(config.company_name || '');
        setCompanyLogo(config.company_logo || '');
        setLogoPreview(config.company_logo || '');
        setProfitPercentage(config.profit_percentage ?? '');
      } catch {
        showToast('加载配置失败', 'error');
      } finally {
        setLoading(false);
      }
    };
    fetchConfig();
  }, []);

  // Upload logo
  const handleLogoUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Preview
    const reader = new FileReader();
    reader.onload = (ev) => setLogoPreview(ev.target.result);
    reader.readAsDataURL(file);

    // Upload
    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await authFetch('/api/config/logo', {
        method: 'POST',
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || 'Logo上传失败', 'error');
        return;
      }
      const newLogoPath = data.path || data.logo || data.file_path || '';
      setCompanyLogo(newLogoPath);
      showToast('Logo上传成功');
    } catch {
      showToast('Logo上传失败', 'error');
    }
  };

  // Save company info
  const handleSaveCompany = async () => {
    setSavingCompany(true);
    try {
      const res = await authFetch('/api/config', {
        method: 'PUT',
        body: JSON.stringify({
          company_name: companyName,
          company_logo: companyLogo,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '保存失败', 'error');
      } else {
        showToast('企业信息已保存');
      }
    } catch {
      showToast('保存失败，请重试', 'error');
    } finally {
      setSavingCompany(false);
    }
  };

  // Save profit config
  const handleSaveProfit = async () => {
    if (profitPercentage === '' || Number(profitPercentage) < 0) {
      showToast('请输入有效的利润比例', 'error');
      return;
    }
    setSavingProfit(true);
    try {
      const res = await authFetch('/api/config', {
        method: 'PUT',
        body: JSON.stringify({
          profit_percentage: Number(profitPercentage),
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '保存失败', 'error');
      } else {
        showToast('利润配置已保存');
      }
    } catch {
      showToast('保存失败，请重试', 'error');
    } finally {
      setSavingProfit(false);
    }
  };

  // Select Excel for import
  const handleImportFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImportFile(file);
    setImportResult(null);
  };

  // Start import Excel
  const handleStartImport = async () => {
    if (!importFile) {
      showToast('请先选择 Excel 文件', 'error');
      return;
    }
    setImporting(true);
    setImportResult(null);

    const formData = new FormData();
    formData.append('file', importFile);

    try {
      const res = await authFetch('/api/contracts/import', {
        method: 'POST',
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '导入失败，请检查文件格式', 'error');
      } else {
        showToast(data.message || '导入成功');
        setImportResult({ type: 'success', text: data.message });
        setImportFile(null);
        if (importInputRef.current) importInputRef.current.value = '';
      }
    } catch (err) {
      showToast('导入失败，请稍后重试', 'error');
    } finally {
      setImporting(false);
    }
  };

  if (loading) {
    return (
      <div className="loading-overlay">
        <div className="loading-spinner"></div>
      </div>
    );
  }

  return (
    <div className="animate-fadeIn">
      {/* Toast */}
      {toast && (
        <div className="toast-container">
          <div className={`toast toast-${toast.type}`}>
            {toast.type === 'success' ? '✅' : '❌'} {toast.message}
          </div>
        </div>
      )}

      <div className="page-header">
        <div>
          <h1 className="page-title">系统配置</h1>
          <p className="page-subtitle">管理企业信息和系统参数</p>
        </div>
      </div>

      {/* Card 1: 企业信息 */}
      <div className="card" style={{ marginBottom: 24 }}>
        <div className="card-header">
          <h3 className="card-title">🏢 企业信息</h3>
        </div>
        <div className="card-body">
          <div className="form-group">
            <label className="form-label">企业名称</label>
            <input
              type="text"
              className="form-input"
              placeholder="请输入企业名称"
              value={companyName}
              onChange={e => setCompanyName(e.target.value)}
              style={{ maxWidth: 480 }}
            />
          </div>

          <div className="form-group">
            <label className="form-label">企业Logo</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
              {/* Logo Preview */}
              <div style={{
                width: 80,
                height: 80,
                borderRadius: 'var(--radius-lg)',
                border: '2px dashed var(--gray-200)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                overflow: 'hidden',
                background: '#ffffff',
                flexShrink: 0,
              }}>
                {logoPreview ? (
                  <img
                    src={logoPreview}
                    alt="企业Logo"
                    style={{ width: '100%', height: '100%', objectFit: 'contain', backgroundColor: '#ffffff', padding: 4 }}
                  />
                ) : (
                  <span style={{ fontSize: 32, opacity: 0.3 }}>🏢</span>
                )}
              </div>
              <div>
                <button
                  type="button"
                  className="btn btn-outline btn-sm"
                  onClick={() => logoInputRef.current?.click()}
                >
                  📁 上传Logo
                </button>
                <input
                  ref={logoInputRef}
                  type="file"
                  accept="image/*"
                  style={{ display: 'none' }}
                  onChange={handleLogoUpload}
                />
                <div className="form-hint" style={{ marginTop: 6 }}>
                  支持 JPG、PNG 格式，建议尺寸 200×200
                </div>
              </div>
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <button
              className="btn btn-primary"
              disabled={savingCompany}
              onClick={handleSaveCompany}
            >
              {savingCompany ? '保存中...' : '💾 保存企业信息'}
            </button>
          </div>
        </div>
      </div>

      {/* Card 2: 利润配置 */}
      <div className="card" style={{ marginBottom: 24 }}>
        <div className="card-header">
          <h3 className="card-title">📊 利润配置</h3>
        </div>
        <div className="card-body">
          <div className="form-group">
            <label className="form-label">预估利润默认比例</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, maxWidth: 240 }}>
              <input
                type="number"
                className="form-input"
                placeholder="请输入比例"
                min="0"
                max="100"
                step="0.1"
                value={profitPercentage}
                onChange={e => setProfitPercentage(e.target.value)}
              />
              <span style={{ fontSize: 18, fontWeight: 600, color: 'var(--gray-500)', flexShrink: 0 }}>%</span>
            </div>
            <div className="form-hint">
              新建合同时，预估利润将自动按此比例计算（合同金额 × 比例）
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <button
              className="btn btn-primary"
              disabled={savingProfit}
              onClick={handleSaveProfit}
            >
              {savingProfit ? '保存中...' : '💾 保存利润配置'}
            </button>
          </div>
        </div>
      </div>

      {/* Card 3: 导入历史合同 (仅管理员可见) */}
      {user?.role === 'admin' && (
        <div className="card">
          <div className="card-header">
            <h3 className="card-title">📥 导入历史合同</h3>
          </div>
          <div className="card-body">
            <p className="form-hint" style={{ marginBottom: 16, fontSize: 14, color: 'var(--gray-600)' }}>
              此功能用于导入以往已通过终审的合同 Excel 记录。系统会自动识别表格内容、自动生成审核记录，并将合同归档至已通过状态。
            </p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <button
                type="button"
                className="btn btn-outline"
                onClick={() => importInputRef.current?.click()}
                disabled={importing}
              >
                📁 选择 Excel 模板/文件
              </button>
              <input
                ref={importInputRef}
                type="file"
                accept=".xlsx, .xls"
                style={{ display: 'none' }}
                onChange={handleImportFileSelect}
              />
              {importFile && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--gray-700)' }}>
                    📄 {importFile.name} ({(importFile.size / 1024).toFixed(1)} KB)
                  </span>
                  <button
                    className="btn btn-primary"
                    disabled={importing}
                    onClick={handleStartImport}
                  >
                    {importing ? '⚡ 正在读取并导入...' : '⚡ 开始导入并归档'}
                  </button>
                </div>
              )}
            </div>
            {importResult && (
              <div style={{
                marginTop: 16,
                padding: 12,
                borderRadius: 'var(--radius-md)',
                background: 'var(--green-50)',
                border: '1px solid var(--green-200)',
                color: 'var(--green-800)',
                fontSize: 14
              }}>
                🎉 {importResult.text}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
