// AdOps Uploader role enforcement component
// Wraps content that should be hidden from adops_uploader role
'use client';
import React from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { createClient } from '@/lib/supabase/client';
import { useState, useEffect } from 'react';

interface RoleGateProps {
  children: React.ReactNode;
  /** Roles that CAN see this content. Default: ['administrator', 'admin'] */
  allowedRoles?: string[];
  /** What to render if role is not allowed. Default: null (hidden) */
  fallback?: React.ReactNode;
}

/**
 * RoleGate — wraps content that should be hidden from adops_uploader.
 * Usage: <RoleGate>$pricing info</RoleGate>
 */
export function RoleGate({ children, allowedRoles = ['administrator', 'admin'], fallback = null }: RoleGateProps) {
  const { user } = useAuth();
  const [role, setRole] = useState<string | null>(null);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    if (!user) { setChecked(true); return; }
    const supabase = createClient();
    supabase.from('user_profiles').select('role').eq('id', user.id).single()
      .then(({ data }) => { setRole(data?.role ?? null); setChecked(true); });
  }, [user]);

  if (!checked) return null;
  if (!role || !allowedRoles.includes(role)) return <>{fallback}</>;
  return <>{children}</>;
}

/**
 * AdopsUploaderView — content visible ONLY to adops_uploader (and admins).
 * Use for IO details, upload interfaces, flight status.
 */
export function AdopsUploaderView({ children }: { children: React.ReactNode }) {
  const { user } = useAuth();
  const [role, setRole] = useState<string | null>(null);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    if (!user) { setChecked(true); return; }
    const supabase = createClient();
    supabase.from('user_profiles').select('role').eq('id', user.id).single()
      .then(({ data }) => { setRole(data?.role ?? null); setChecked(true); });
  }, [user]);

  if (!checked) return null;
  if (!role || !['administrator', 'admin', 'adops_uploader'].includes(role)) return null;
  return <>{children}</>;
}

/**
 * IOBannerUploadGate — enforces IO selection before banner upload.
 * adops_uploader must select an active IO before upload is accepted.
 */
export function IOBannerUploadGate({ children, onIOSelected }: { children: React.ReactNode; onIOSelected?: (io: any) => void }) {
  const [ios, setIos] = useState<any[]>([]);
  const [selectedIO, setSelectedIO] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetch('/api/adops/rmp/ios?status=active')
      .then(r => r.json())
      .then(d => { setIos(d.ios ?? []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  function handleSelect(id: string) {
    const io = ios.find((i: any) => i.id === id);
    if (!io) { setError('Invalid IO selected'); return; }
    setSelectedIO(io);
    setError('');
    onIOSelected?.(io);
  }

  if (loading) return <div className="text-xs text-[#555]">Loading IOs…</div>;

  if (!selectedIO) {
    return (
      <div className="space-y-2">
        <div className="bg-yellow-400/5 border border-yellow-400/20 rounded p-3">
          <p className="text-xs text-yellow-400 font-medium">Insertion Order Required</p>
          <p className="text-xs text-[#888] mt-1">Select an active IO before uploading.</p>
        </div>
        {ios.length === 0 ? (
          <p className="text-xs text-red-400">Banner upload requires an active Insertion Order. No active IOs found.</p>
        ) : (
          <select onChange={e => handleSelect(e.target.value)} className="w-full px-2 py-1.5 bg-[#0a0a0a] border border-[#DCE6F2] rounded text-xs text-white focus:outline-none focus:border-[#1D4ED8]">
            <option value="">Select IO…</option>
            {ios.map((io: any) => (
              <option key={io.id} value={io.id}>
                {io.existing_io_id} — {io.rmp_clients?.company_name ?? 'Unknown'} ({io.flight_status})
              </option>
            ))}
          </select>
        )}
        {error && <p className="text-xs text-red-400">{error}</p>}
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="bg-green-400/5 border border-green-400/20 rounded p-2 flex items-center justify-between">
        <div>
          <p className="text-xs text-green-400 font-medium">IO: {selectedIO.existing_io_id}</p>
          <p className="text-xs text-[#888]">{selectedIO.rmp_clients?.company_name} — {selectedIO.rmp_products?.name}</p>
          {selectedIO.rmp_products?.dimensions && (
            <p className="text-xs text-[#555]">Required dimensions: {selectedIO.rmp_products.dimensions}</p>
          )}
        </div>
        <button onClick={() => setSelectedIO(null)} className="text-xs text-[#555] hover:text-white">Change</button>
      </div>
      {children}
    </div>
  );
}
