'use client';

import { ReadonlyLeagueInfo } from '@/components/leagues/ReadonlyLeagueInfo';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
import { ServiceFactory } from '@/lib/services/ServiceFactory';
import type { LeagueConfigFormModel } from '@/lib/types/LeagueConfigFormModel';
import type { DriverDTO } from '@/lib/types/DriverDTO';
import { LeagueSettingsViewModel } from '@/lib/view-models/LeagueSettingsViewModel';
import { AlertTriangle, Settings, UserCog } from 'lucide-react';
import { useParams, useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';

export default function LeagueSettingsPage() {
  const params = useParams();
  const leagueId = params.id as string;
  const currentDriverId = useEffectiveDriverId();

  const [settings, setSettings] = useState<LeagueSettingsViewModel | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  const [showTransferDialog, setShowTransferDialog] = useState(false);
  const [selectedNewOwner, setSelectedNewOwner] = useState<string>('');
  const [transferring, setTransferring] = useState(false);
  const router = useRouter();

  const serviceFactory = useMemo(() => new ServiceFactory(process.env.NEXT_PUBLIC_API_BASE_URL || ''), []);
  const leagueMembershipService = useMemo(() => serviceFactory.createLeagueMembershipService(), [serviceFactory]);
  const leagueSettingsService = useMemo(() => serviceFactory.createLeagueSettingsService(), [serviceFactory]);

  useEffect(() => {
    async function checkAdmin() {
      const memberships = await leagueMembershipService.fetchLeagueMemberships(leagueId);
      const membership = leagueMembershipService.getMembership(leagueId, currentDriverId);
      setIsAdmin(membership ? 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 ownerSummary = settings?.owner || null;

  const handleTransferOwnership = async () => {
    if (!selectedNewOwner || !settings) return;

    setTransferring(true);
    try {
      await leagueSettingsService.transferOwnership(leagueId, currentDriverId, selectedNewOwner);

      setShowTransferDialog(false);
      router.refresh();
    } catch (err) {
      console.error('Failed to transfer ownership:', err);
      alert(err instanceof Error ? err.message : 'Failed to transfer ownership');
    } finally {
      setTransferring(false);
    }
  };

  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} />

        {/* League Owner - Compact */}
        <div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
          <h3 className="text-sm font-semibold text-gray-400 mb-3">League Owner</h3>
          {ownerSummary ? (
            <DriverSummaryPill
              driver={ownerSummary.driver}
              rating={ownerSummary.rating}
              rank={ownerSummary.rank}
            />
          ) : (
            <p className="text-sm text-gray-500">Loading owner details...</p>
          )}
        </div>

        {/* Transfer Ownership - Owner Only */}
        {settings.league.ownerId === currentDriverId && settings.members.length > 0 && (
          <div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
            <div className="flex items-center gap-2 mb-3">
              <UserCog className="w-4 h-4 text-gray-400" />
              <h3 className="text-sm font-semibold text-gray-400">Transfer Ownership</h3>
            </div>
            <p className="text-xs text-gray-500 mb-4">
              Transfer league ownership to another active member. You will become an admin.
            </p>

            {!showTransferDialog ? (
              <Button
                variant="secondary"
                onClick={() => setShowTransferDialog(true)}
              >
                Transfer Ownership
              </Button>
            ) : (
              <div className="space-y-3">
                <select
                  value={selectedNewOwner}
                  onChange={(e) => setSelectedNewOwner(e.target.value)}
                  className="w-full rounded-lg border border-charcoal-outline bg-charcoal-card px-3 py-2 text-sm text-white focus:border-primary-blue focus:outline-none"
                >
                  <option value="">Select new owner...</option>
                  {settings.members.map((member) => (
                    <option key={member.id} value={member.id}>
                      {member.name}
                    </option>
                  ))}
                </select>

                <div className="flex gap-2">
                  <Button
                    variant="primary"
                    onClick={handleTransferOwnership}
                    disabled={!selectedNewOwner || transferring}
                  >
                    {transferring ? 'Transferring...' : 'Confirm Transfer'}
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={() => {
                      setShowTransferDialog(false);
                      setSelectedNewOwner('');
                    }}
                    disabled={transferring}
                  >
                    Cancel
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}