import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { LinkIcon, Check, ExternalLink, Terminal, AlertTriangle, Copy, CheckCircle } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Avatar } from '@/components/ui/Avatar';
import { Badge } from '@/components/ui/Badge';
import { useToast } from '@/components/ui/Toast';
import { authAPI } from '@/api/client';
import { formatRelativeTime } from '@/lib/constants';
import { cn } from '@/lib/cn';

const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';

interface SteamLinkCardProps {
  steamId: string | null;
  personaName: string | null;
  avatarUrl: string | null;
  linkedAt: string | null;
  onLinked?: () => void;
}

export function SteamLinkCard({ steamId, personaName, avatarUrl, linkedAt, onLinked }: SteamLinkCardProps) {
  const [loading, setLoading] = useState(false);
  const [devMode, setDevMode] = useState(false);
  const [manualSteamId, setManualSteamId] = useState('');
  const [error, setError] = useState('');
  const { toast } = useToast();
  const isLinked = !!steamId;

  async function handleLink() {
    if (isLocalhost) {
      setDevMode(true);
      return;
    }
    setLoading(true);
    try {
      const { data } = await authAPI.steamRedirect();
      window.location.href = data.redirect_url;
    } catch {
      setLoading(false);
    }
  }

  async function handleDevLink() {
    const trimmed = manualSteamId.trim();
    if (!trimmed) {
      setError('Please enter a Steam ID 64');
      return;
    }
    if (trimmed.length !== 17 || !trimmed.startsWith('7656')) {
      setError('Invalid format. Steam ID 64 is a 17-digit number starting with 7656');
      return;
    }

    setError('');
    setLoading(true);
    try {
      await authAPI.steamDevLink({ steam_id: trimmed });
      toast('Steam account linked successfully!', 'success');
      onLinked?.();
      setDevMode(false);
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Failed to link Steam account';
      setError(msg);
      toast(msg, 'error');
    } finally {
      setLoading(false);
    }
  }

  if (isLinked) {
    return (
      <Card>
        <h3 className="text-sm font-medium text-text-secondary uppercase tracking-wider mb-4">Steam Account</h3>
        <div className="flex items-center gap-4">
          <Avatar src={avatarUrl} username={personaName || 'Steam'} size="lg" />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="text-base font-semibold text-text-primary truncate">{personaName}</span>
              <Badge variant="success" dot>Verified</Badge>
            </div>
            <p className="text-sm text-text-muted font-mono mt-0.5">{steamId}</p>
            {linkedAt && (
              <p className="text-xs text-text-muted mt-1">
                Linked {formatRelativeTime(linkedAt)}
              </p>
            )}
          </div>
          <a
            href={`https://steamcommunity.com/profiles/${steamId}`}
            target="_blank"
            rel="noopener noreferrer"
            className="p-2 text-text-muted hover:text-text-secondary transition-colors"
          >
            <ExternalLink className="w-4 h-4" />
          </a>
        </div>
      </Card>
    );
  }

  return (
    <Card className={cn(devMode ? 'border-amber-500/20' : 'border-amber-500/30 animate-pulse-glow')}>
      <h3 className="text-sm font-medium text-text-secondary uppercase tracking-wider mb-3">Steam Account</h3>

      <AnimatePresence mode="wait">
        {!devMode ? (
          <motion.div
            key="link-prompt"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0, height: 0 }}
          >
            <div className="flex items-start gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-amber-500/10 flex items-center justify-center flex-shrink-0">
                <LinkIcon className="w-5 h-5 text-amber-500" />
              </div>
              <div>
                <p className="text-sm text-text-primary font-medium">Link your Steam account to queue for matches</p>
                <p className="text-xs text-text-muted mt-0.5">Your Steam64 ID will be used for game server whitelisting.</p>
              </div>
            </div>
            <Button onClick={handleLink} loading={loading} className="w-full">
              <LinkIcon className="w-4 h-4" />
              {isLocalhost ? 'Link Steam (Dev Mode)' : 'Sign in with Steam'}
            </Button>
          </motion.div>
        ) : (
          <motion.div
            key="dev-form"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ type: 'spring', stiffness: 300, damping: 22 }}
          >
            <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 mb-4">
              <Terminal className="w-4 h-4 text-amber-400 flex-shrink-0" />
              <p className="text-xs text-amber-300 font-medium">
                Localhost mode, Steam OAuth is unavailable on localhost. Enter your Steam ID 64 manually.
              </p>
            </div>

            <div className="space-y-3 mb-5">
              <p className="text-xs text-text-muted font-medium">How to find your Steam ID 64:</p>
              <ol className="text-xs text-text-muted space-y-1.5 list-decimal list-inside">
                <li>
                  Go to{' '}
                  <a
                    href="https://steamid.io/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[#ff6b2c] hover:text-[#ff8a50] font-semibold transition-colors inline-flex items-center gap-1"
                  >
                    steamid.io <ExternalLink className="w-3 h-3" />
                  </a>
                </li>
                <li>Enter your Steam profile URL or username</li>
                <li>Copy the <span className="text-text-secondary font-mono font-semibold">steamID64</span> value (e.g. 76561198012345678)</li>
              </ol>
            </div>

            <div className="space-y-3">
              <Input
                label="Steam ID 64"
                icon={<Terminal className="w-4 h-4" />}
                placeholder="76561198012345678"
                value={manualSteamId}
                onChange={(e) => { setManualSteamId(e.target.value); setError(''); }}
                error={error}
                autoFocus
              />
              <div className="flex gap-2">
                <Button onClick={handleDevLink} loading={loading} className="flex-1">
                  <CheckCircle className="w-4 h-4" />
                  Link Account
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => { setDevMode(false); setError(''); setManualSteamId(''); }}
                  className="px-4"
                >
                  Cancel
                </Button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </Card>
  );
}
