'use client';

import { ReadonlyLeagueInfo } from '@/components/leagues/ReadonlyLeagueInfo';
import LeagueOwnershipTransfer from '@/components/leagues/LeagueOwnershipTransfer';
import Card from '@/components/ui/Card';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
import { useServices } from '@/lib/services/ServiceProvider';
import { LeagueSettingsViewModel } from '@/lib/view-models/LeagueSettingsViewModel';
import { AlertTriangle, Settings } from 'lucide-react';
import { useParams, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function LeagueSettingsPage() {
  const params = useParams();
  const leagueId = params.id as string;
  const currentDriverId = useEffectiveDriverId();
  const { leagueMembershipService, leagueSettingsService } = useServices();

  const [settings, setSettings] = useState<LeagueSettingsViewModel | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  const router = useRouter();

  useEffect(() => {
    async function checkAdmin() {
      const membership = leagueMembershipService.getMembership(leagueId, currentDriverId);
      setIsAdmin(membership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(membership.role) : false);
    }
    checkAdmin();
  }, [leagueId, currentDriverId, leagueMembershipService]);

  useEffect(() => {
    async function loadSettings() {
      setLoading(true);
      try {
        const settingsData = await leagueSettingsService.getLeagueSettings(leagueId);
        if (settingsData) {
          setSettings(settingsData);
        }
      } catch (err) {
        console.error('Failed to load league settings:', err);
      } finally {
        setLoading(false);
      }
    }

    if (isAdmin) {
      loadSettings();
    }
  }, [leagueId, isAdmin, leagueSettingsService]);


  const handleTransferOwnership = async (newOwnerId: string) => {
    try {
      await leagueSettingsService.transferOwnership(leagueId, currentDriverId, newOwnerId);
      router.refresh();
    } catch (err) {
      throw err; // Let the component handle the error
    }
  };

  if (!isAdmin) {
    return (
      <Card>
        <div className="text-center py-12">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-iron-gray/50 flex items-center justify-center">
            <AlertTriangle className="w-8 h-8 text-warning-amber" />
          </div>
          <h3 className="text-lg font-medium text-white mb-2">Admin Access Required</h3>
          <p className="text-sm text-gray-400">
            Only league admins can access settings.
          </p>
        </div>
      </Card>
    );
  }

  if (loading) {
    return (
      <Card>
        <div className="py-6 text-sm text-gray-400">Loading configuration…</div>
      </Card>
    );
  }

  if (!settings) {
    return (
      <Card>
        <div className="py-6 text-sm text-gray-500">
          Unable to load league configuration for this demo league.
        </div>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10">
          <Settings className="w-6 h-6 text-primary-blue" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">League Settings</h1>
          <p className="text-sm text-gray-400">Manage your league configuration</p>
        </div>
      </div>



      {/* READONLY INFORMATION SECTION - Compact */}
      <div className="space-y-4">
        <ReadonlyLeagueInfo league={settings.league} configForm={settings.config} />

        <LeagueOwnershipTransfer
          settings={settings}
          currentDriverId={currentDriverId}
          onTransferOwnership={handleTransferOwnership}
        />
      </div>
    </div>
  );
}