import React, { useState } from 'react';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import Button from '@/components/ui/Button';
import { UserCog } from 'lucide-react';
import { LeagueSettingsViewModel } from '@/lib/view-models/LeagueSettingsViewModel';
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';

interface LeagueOwnershipTransferProps {
  settings: LeagueSettingsViewModel;
  currentDriverId: string;
  onTransferOwnership: (newOwnerId: string) => Promise<void>;
}

export default function LeagueOwnershipTransfer({
  settings,
  currentDriverId,
  onTransferOwnership
}: LeagueOwnershipTransferProps) {
  const [showTransferDialog, setShowTransferDialog] = useState(false);
  const [selectedNewOwner, setSelectedNewOwner] = useState<string>('');
  const [transferring, setTransferring] = useState(false);

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

    setTransferring(true);
    try {
      await onTransferOwnership(selectedNewOwner);
      setShowTransferDialog(false);
      setSelectedNewOwner('');
    } catch (err) {
      console.error('Failed to transfer ownership:', err);
      alert(err instanceof Error ? err.message : 'Failed to transfer ownership');
    } finally {
      setTransferring(false);
    }
  };

  const ownerSummary = settings.owner;

  return (
    <div className="space-y-4">
      {/* League Owner */}
      <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={new DriverViewModel({
              id: ownerSummary.driver.id,
              name: ownerSummary.driver.name,
              avatarUrl: (ownerSummary.driver as any).avatarUrl ?? null,
              iracingId: ownerSummary.driver.iracingId,
              country: ownerSummary.driver.country,
              bio: ownerSummary.driver.bio,
              joinedAt: ownerSummary.driver.joinedAt,
            })}
            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.driver.id} value={member.driver.id}>
                    {member.driver.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>
  );
}