/**
 * ParentViewToggle — small avatar-dropdown affordance.
 *
 * Phase 1 PR 1 (2026-07-22) — parent-as-staff UI.
 *
 * Appears in the user menu (top-right avatar dropdown) when the current
 * user has at least one parent_students row (i.e. a child of theirs is
 * enrolled at the school). Clicking the toggle flips a local "view as
 * parent" flag in the auth store, swaps the active dashboard to the
 * parent view, and reverts on toggle off. The underlying role does NOT
 * change — the user is still a teacher, just looking at the parent side.
 *
 * The flag is per-session (in-memory + sessionStorage) so a refresh
 * starts you back at your primary role.
 */

import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Users, ArrowLeftRight } from 'lucide-react';
import api from '../store/api';
import { useAuthStore } from '../store/auth';

const STORAGE_KEY = 'parent-view-active';

export const ParentViewToggle: React.FC = () => {
  const { user } = useAuthStore();
  const navigate = useNavigate();
  const location = useLocation();
  const [childCount, setChildCount] = useState<number | null>(null);
  const [viewAsParent, setViewAsParent] = useState<boolean>(() => {
    try { return sessionStorage.getItem(STORAGE_KEY) === '1'; } catch { return false; }
  });

  useEffect(() => {
    if (!user) return;
    api.get('/users/me/children')
      .then((r) => setChildCount(r.data?.children?.length ?? 0))
      .catch(() => setChildCount(0));
  }, [user]);

  // Don't render anything if the user has no linked children.
  if (childCount === null || childCount === 0) return null;

  const toggle = () => {
    const next = !viewAsParent;
    setViewAsParent(next);
    try { sessionStorage.setItem(STORAGE_KEY, next ? '1' : '0'); } catch { /* ignore */ }
    if (next) {
      navigate('/dashboard/parent');
    } else if (location.pathname.startsWith('/dashboard/parent')) {
      // Revert to primary role's dashboard
      const primary = user?.role || 'school_admin';
      const roleRoutes: Record<string, string> = {
        school_admin: '/dashboard/admin',
        systems_admin: '/dashboard/admin',
        principal: '/dashboard/admin',
        hr: '/dashboard/hr',
        bursar: '/dashboard/finance',
        teacher: '/dashboard/teacher',
        librarian: '/dashboard/librarian',
        clubs_head: '/dashboard/clubs_head',
        student: '/dashboard/student',
      };
      navigate(roleRoutes[primary] || '/dashboard/admin');
    }
  };

  return (
    <button
      type="button"
      onClick={toggle}
      className={`w-full flex items-center gap-3 px-3 py-2 rounded-xl text-sm font-bold transition-colors ${
        viewAsParent
          ? 'bg-amber-500/10 text-amber-700 dark:text-amber-300'
          : 'text-text-secondary hover:bg-background-alt'
      }`}
    >
      {viewAsParent ? <ArrowLeftRight size={16} /> : <Users size={16} />}
      <span className="flex-1 text-left">
        {viewAsParent ? 'Back to my role' : `View as parent (${childCount})`}
      </span>
    </button>
  );
};

export default ParentViewToggle;
