"use client";

import React from 'react';
import { useRouter } from 'next/router'; // For Pages Router
import { useAuth } from '@/context/AuthContext';
import IndividualClientPage from '@/components/IndividualClientPage';
import LoginPage from '@/components/LoginPage';
import { UserRoles } from '@/types';
import {Button} from '@/components/ui/button';

const ClientDetailPage: React.FC = () => {
  const router = useRouter();
  const { clientId } = router.query;
  const { user, loading, token, hasPermission, logout } = useAuth(); // Call useAuth once here

  if (loading) {
    return <div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">Loading Authentication...</div>;
  }

  if (!user || !token || !hasPermission(UserRoles.MOD)) {
    // Redirect to login or show access denied if not authenticated or authorized
    return (
      <div className="min-h-screen bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 font-sans">
        <header className="flex justify-between items-center p-4 bg-white dark:bg-gray-800 shadow-md">
          <h1 className="text-xl font-bold">Radio App Admin</h1>
        </header>
        <main className="p-6">
          {!user ? (
            <LoginPage />
          ) : (
            <div className="text-center text-red-500 text-lg">
              You do not have permission to view this page. Your role: {user.role}. Required: {UserRoles.MOD}.
            </div>
          )}
        </main>
      </div>
    );
  }

  // Ensure clientId is a string before passing
  const clientIdentifier = Array.isArray(clientId) ? clientId[0] : clientId;

  if (!clientIdentifier) {
    return <div className="text-center text-red-500 text-lg mt-10">Client ID not found in URL.</div>;
  }

  return (
    <div className="min-h-screen bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 font-sans">
      <header className="flex justify-between items-center p-4 bg-white dark:bg-gray-800 shadow-md">
        <h1 className="text-xl font-bold">Radio App Admin</h1>
        <div className="flex items-center space-x-4">
          <span className="text-sm">Logged in as: {user.username} ({user.role})</span>
          <Button onClick={() => router.push('/')} variant="outline">Back to Management</Button>
          <Button onClick={logout} variant="outline">Logout</Button> {/* Use the destructured logout */}
        </div>
      </header>
      <main className="p-6">
        <IndividualClientPage clientId={clientIdentifier} token={token} logoutUser={logout} />
      </main>
    </div>
  );
};

export default ClientDetailPage;