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

const ROLES = ['employee', 'supervisor', 'finance', 'secretary'];

const MENU_ITEMS = [
  { key: 'dashboard', label: '工作台' },
  { key: 'contracts', label: '合同流转' },
  { key: 'partners', label: '合作单位' },
  { key: 'users', label: '用户管理' },
  { key: 'departments', label: '部门管理' },
  { key: 'settings', label: '系统配置' },
  { key: 'permissions', label: '权限配置' },
];

export default function PermissionsPage() {
  const user = useUser();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState(null);

  // Permission matrix: { role: { menu_key: 0|1 } }
  const [matrix, setMatrix] = useState({});

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

  // Fetch permissions
  useEffect(() => {
    const fetchPermissions = async () => {
      try {
        const res = await authFetch('/api/permissions');
        const data = await res.json();
        const perms = data.permissions || data || [];

        // Build matrix
        const m = {};
        ROLES.forEach(role => {
          m[role] = {};
          MENU_ITEMS.forEach(menu => {
            m[role][menu.key] = 0;
          });
        });

        perms.forEach(p => {
          if (m[p.role] !== undefined && MENU_ITEMS.find(mi => mi.key === p.menu_key)) {
            m[p.role][p.menu_key] = p.visible ? 1 : 0;
          }
        });

        setMatrix(m);
      } catch {
        showToast('加载权限配置失败', 'error');
      } finally {
        setLoading(false);
      }
    };
    fetchPermissions();
  }, []);

  const togglePermission = (role, menuKey) => {
    setMatrix(prev => ({
      ...prev,
      [role]: {
        ...prev[role],
        [menuKey]: prev[role][menuKey] ? 0 : 1,
      },
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      // Build permissions array
      const permissions = [];
      ROLES.forEach(role => {
        MENU_ITEMS.forEach(menu => {
          permissions.push({
            role,
            menu_key: menu.key,
            visible: matrix[role]?.[menu.key] || 0,
          });
        });
      });

      const res = await authFetch('/api/permissions', {
        method: 'PUT',
        body: JSON.stringify({ permissions }),
      });
      const data = await res.json();

      if (!res.ok) {
        showToast(data.error || '保存失败', 'error');
      } else {
        showToast('权限配置已保存');
      }
    } catch {
      showToast('保存失败，请重试', 'error');
    } finally {
      setSaving(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>
        <button
          className="btn btn-primary"
          disabled={saving}
          onClick={handleSave}
        >
          {saving ? '保存中...' : '💾 保存配置'}
        </button>
      </div>

      <div className="card">
        <div className="card-body" style={{ padding: 0 }}>
          <div className="table-container">
            <table className="permission-table">
              <thead>
                <tr>
                  <th style={{ minWidth: 120 }}>角色</th>
                  {MENU_ITEMS.map(menu => (
                    <th key={menu.key}>{menu.label}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {ROLES.map(role => (
                  <tr key={role}>
                    <td>
                      <span style={{ fontWeight: 600, color: 'var(--text-dark)' }}>
                        {ROLE_NAMES[role] || role}
                      </span>
                    </td>
                    {MENU_ITEMS.map(menu => (
                      <td key={menu.key}>
                        <input
                          type="checkbox"
                          className="permission-checkbox"
                          checked={matrix[role]?.[menu.key] === 1}
                          onChange={() => togglePermission(role, menu.key)}
                        />
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div style={{
        marginTop: 16,
        padding: '12px 16px',
        background: 'var(--info-light)',
        borderRadius: 'var(--radius-md)',
        fontSize: 13,
        color: 'var(--info)',
        display: 'flex',
        alignItems: 'center',
        gap: 8,
      }}>
        ℹ️ 管理员（admin）默认拥有所有菜单权限，无需单独配置。修改后请点击"保存配置"按钮使更改生效。
      </div>
    </div>
  );
}
