import { useState } from 'react';
import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type PermissionItem = {
  id: number;
  key: string;
  label: string;
  granted: boolean;
};

type PermissionGroup = {
  group: string;
  items: PermissionItem[];
};

type Props = {
  targetUser: {
    id: number;
    name: string;
    username: string;
  };
  groups: PermissionGroup[];
};

const groupIcons: Record<string, string> = {
  'دانش‌آموزان': 'bi-person-badge',
  'کلاس‌ها': 'bi-door-open',
  'حضور و غیاب': 'bi-clipboard-check',
  'نمره‌دهی': 'bi-patch-check',
  'تکالیف': 'bi-journal-text',
  'امتحانات': 'bi-pencil-square',
  'SMS': 'bi-chat-dots',
  'رأی‌گیری': 'bi-ballot',
  'گزارش‌ها': 'bi-bar-chart',
};

export default function MoavenPermissions({ targetUser, groups }: Props) {
  const [granted, setGranted] = useState<Set<number>>(
    () => new Set(
      groups.flatMap((g) => g.items.filter((i) => i.granted).map((i) => i.id))
    )
  );
  const [saving, setSaving] = useState(false);

  function toggle(id: number) {
    setGranted((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  }

  function toggleGroup(items: PermissionItem[]) {
    const allGranted = items.every((i) => granted.has(i.id));
    setGranted((prev) => {
      const next = new Set(prev);
      if (allGranted) {
        items.forEach((i) => next.delete(i.id));
      } else {
        items.forEach((i) => next.add(i.id));
      }
      return next;
    });
  }

  function handleSave() {
    setSaving(true);
    router.put(
      `/school/users/${targetUser.id}/permissions`,
      { permission_ids: [...granted] },
      {
        preserveScroll: true,
        onFinish: () => setSaving(false),
      }
    );
  }

  const totalGranted = granted.size;
  const totalAvailable = groups.reduce((sum, g) => sum + g.items.length, 0);

  return (
    <AppLayout title={`دسترسی‌های ${targetUser.name}`}>
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-shield-lock" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              مدیریت دسترسی معاون
            </h2>
            <p>
              <strong>{targetUser.name}</strong>
              {' '}({targetUser.username}) —{' '}
              {totalGranted} از {totalAvailable} دسترسی فعال
            </p>
          </div>
          <div className="action-row">
            <a className="btn btn-ghost" href="/school/users">
              <i className="bi bi-arrow-right" /> بازگشت
            </a>
            <button
              className="btn btn-primary"
              disabled={saving}
              type="button"
              onClick={handleSave}
            >
              {saving
                ? <><i className="bi bi-arrow-repeat" /> در حال ذخیره...</>
                : <><i className="bi bi-check-circle" /> ذخیره دسترسی‌ها</>
              }
            </button>
          </div>
        </section>

        <section
          className="panel-card"
          style={{
            background: 'linear-gradient(135deg, var(--color-primary-soft-2), var(--color-accent-soft))',
            border: '1px solid var(--color-primary-soft)',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', flexWrap: 'wrap' }}>
            <div className="icon-badge" style={{ flexShrink: 0 }}>
              <i className="bi bi-person-gear" />
            </div>
            <div>
              <strong style={{ fontSize: '1rem' }}>راهنما</strong>
              <p style={{ margin: '0.25rem 0 0', fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
                دسترسی‌های تیک‌خورده برای این معاون فعال می‌شوند. تغییرات بعد از کلیک «ذخیره» اعمال می‌شوند.
                owner اصلی همیشه دسترسی کامل دارد.
              </p>
            </div>
            <div style={{ marginRight: 'auto', textAlign: 'left' }}>
              <div
                style={{
                  background: 'white',
                  borderRadius: 'var(--radius-md)',
                  padding: '0.5rem 1rem',
                  border: '1px solid var(--color-border)',
                  minWidth: 120,
                  textAlign: 'center',
                }}
              >
                <div style={{ fontSize: '1.5rem', fontWeight: 900, color: 'var(--color-primary)' }}>
                  {totalGranted}
                </div>
                <div style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)' }}>
                  از {totalAvailable} دسترسی
                </div>
              </div>
            </div>
          </div>
        </section>

        <div className="card-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))' }}>
          {groups.map((group) => {
            const allGranted = group.items.every((i) => granted.has(i.id));
            const someGranted = group.items.some((i) => granted.has(i.id));
            return (
              <article key={group.group} className="panel-card" style={{ padding: '1.25rem' }}>
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    marginBottom: '1rem',
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
                    <span
                      style={{
                        alignItems: 'center',
                        background: someGranted ? 'var(--color-primary-soft)' : 'var(--color-surface-muted)',
                        borderRadius: 'var(--radius-sm)',
                        color: someGranted ? 'var(--color-primary-active)' : 'var(--color-text-muted)',
                        display: 'inline-flex',
                        fontSize: '1rem',
                        height: 36,
                        justifyContent: 'center',
                        transition: 'background 0.2s, color 0.2s',
                        width: 36,
                      }}
                    >
                      <i className={`bi ${groupIcons[group.group] ?? 'bi-shield'}`} />
                    </span>
                    <strong style={{ fontSize: '0.95rem' }}>{group.group}</strong>
                  </div>
                  <label
                    style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', cursor: 'pointer', fontSize: '0.82rem', color: 'var(--color-text-muted)' }}
                    title={allGranted ? 'حذف همه' : 'انتخاب همه'}
                  >
                    <input
                      type="checkbox"
                      checked={allGranted}
                      ref={(el) => {
                        if (el) el.indeterminate = someGranted && !allGranted;
                      }}
                      onChange={() => toggleGroup(group.items)}
                      style={{ accentColor: 'var(--color-primary)', width: 16, height: 16, cursor: 'pointer' }}
                    />
                    همه
                  </label>
                </div>
                <div style={{ display: 'grid', gap: '0.5rem' }}>
                  {group.items.map((item) => {
                    const isGranted = granted.has(item.id);
                    return (
                      <label
                        key={item.id}
                        style={{
                          alignItems: 'center',
                          background: isGranted ? 'var(--color-primary-soft)' : 'var(--color-bg-soft)',
                          border: `1.5px solid ${isGranted ? 'var(--color-primary-soft)' : 'var(--color-border)'}`,
                          borderRadius: 'var(--radius-sm)',
                          cursor: 'pointer',
                          display: 'flex',
                          gap: '0.75rem',
                          padding: '0.65rem 0.9rem',
                          transition: 'background 0.15s, border-color 0.15s',
                          userSelect: 'none',
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={isGranted}
                          onChange={() => toggle(item.id)}
                          style={{ accentColor: 'var(--color-primary)', width: 16, height: 16, cursor: 'pointer', flexShrink: 0 }}
                        />
                        <span style={{ fontSize: '0.875rem', fontWeight: isGranted ? 700 : 400, color: isGranted ? 'var(--color-primary-active)' : 'var(--color-text)' }}>
                          {item.label}
                        </span>
                        {isGranted && (
                          <i className="bi bi-check2-circle" style={{ marginRight: 'auto', color: 'var(--color-primary)', fontSize: '0.9rem' }} />
                        )}
                      </label>
                    );
                  })}
                </div>
              </article>
            );
          })}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
          <a className="btn btn-ghost" href="/school/users">لغو</a>
          <button
            className="btn btn-primary"
            disabled={saving}
            type="button"
            onClick={handleSave}
            style={{ minWidth: 160 }}
          >
            {saving
              ? <><i className="bi bi-arrow-repeat" /> در حال ذخیره...</>
              : <><i className="bi bi-check-circle" /> ذخیره دسترسی‌ها</>
            }
          </button>
        </div>
      </div>
    </AppLayout>
  );
}
