import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, Ban, AlertTriangle, Shield, Unlink, Edit } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Avatar } from '@/components/ui/Avatar';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { adminAPI } from '@/api/client';
import { formatNumber, formatRelativeTime } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function UserDetail() {
  const { id } = useParams<{ id: string }>();
  const { toast } = useToast();
  const [user, setUser] = useState<any>(null);
  const [history, setHistory] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [banModal, setBanModal] = useState(false);
  const [banReason, setBanReason] = useState('');
  const [banType, setBanType] = useState('temp');
  const [banDuration, setBanDuration] = useState('24h');

  useEffect(() => {
    if (!id) return;
    Promise.all([
      adminAPI.getUser(id).then(({ data }) => setUser(data.user || data)),
      adminAPI.getUserHistory(id).then(({ data }) => setHistory(data.history || [])).catch(() => {}),
    ]).finally(() => setLoading(false));
  }, [id]);

  async function handleBan() {
    if (!id || !banReason) return;
    try {
      await adminAPI.banUser(id, { type: banType, reason: banReason, duration: banType === 'temp' ? banDuration : undefined });
      toast('Ban issued successfully', 'success');
      setBanModal(false);
    } catch {
      toast('Failed to issue ban', 'error');
    }
  }

  if (loading) return <div className="p-6 space-y-4"><SkeletonCard /><SkeletonCard /></div>;
  if (!user) return <div className="p-6 text-text-muted">User not found.</div>;

  return (
    <div className="p-6">
      <Link to="/admin/users" className="inline-flex items-center gap-1.5 text-sm text-text-muted hover:text-text-secondary transition-colors mb-6">
        <ArrowLeft className="w-4 h-4" /> Back to Users
      </Link>

      <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-6">
        <motion.div variants={staggerItem}>
          <Card className="flex flex-col sm:flex-row items-center sm:items-start gap-6">
            <Avatar src={user.steam_avatar_url} username={user.username} size="xl" />
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <h1 className="text-xl font-bold text-text-primary">{user.username}</h1>
                <Badge variant={user.role === 'owner' ? 'warning' : user.role === 'admin' ? 'info' : 'default'}>{user.role}</Badge>
                {user.tier !== 'normal' && <Badge variant={user.tier === 'vip' ? 'vip' : 'premium'}>{user.tier}</Badge>}
              </div>
              <p className="text-sm text-text-muted">{user.email}</p>
              <p className="text-sm text-text-muted">MMR: {formatNumber(user.mmr)} · Matches: {user.matches_played} · W/L: {user.wins}/{user.losses}</p>
              {user.steam_id && <p className="text-xs text-text-muted font-mono mt-1">Steam: {user.steam_id}</p>}
            </div>
            <div className="flex flex-wrap gap-2">
              <Button variant="danger" size="sm" onClick={() => setBanModal(true)}>
                <Ban className="w-3.5 h-3.5" /> Ban
              </Button>
              <Button variant="secondary" size="sm" onClick={() => {
                adminAPI.warnUser(user.id, { reason: 'Warning from admin' }).then(() => toast('Warning issued', 'success'));
              }}>
                <AlertTriangle className="w-3.5 h-3.5" /> Warn
              </Button>
              {user.steam_id && (
                <Button variant="secondary" size="sm" onClick={() => {
                  adminAPI.unlinkSteam(user.id).then(() => toast('Steam unlinked', 'success'));
                }}>
                  <Unlink className="w-3.5 h-3.5" /> Unlink Steam
                </Button>
              )}
            </div>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem}>
          <Card>
            <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest mb-4">History</h2>
            {history.length > 0 ? (
              <div className="space-y-3">
                {history.map((item, i) => (
                  <div key={i} className="flex items-start gap-3 py-2 border-b border-white/[0.03] last:border-0">
                    <Badge variant={item.type === 'ban' ? 'danger' : item.type === 'warning' ? 'warning' : 'default'}>
                      {item.type}
                    </Badge>
                    <div className="flex-1">
                      <p className="text-sm text-text-primary">{item.reason}</p>
                      <p className="text-xs text-text-muted">{item.created_at ? formatRelativeTime(item.created_at) : ''}</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-text-muted">No history records.</p>
            )}
          </Card>
        </motion.div>
      </motion.div>

      <Modal open={banModal} onClose={() => setBanModal(false)} title="Issue Ban">
        <div className="space-y-4">
          <Select
            label="Ban Type"
            value={banType}
            onChange={setBanType}
            options={[
              { value: 'temp', label: 'Temporary' },
              { value: 'perm', label: 'Permanent' },
              { value: 'game', label: 'Game Ban' },
              { value: 'full', label: 'Full Ban' },
            ]}
          />
          {banType === 'temp' && (
            <Select
              label="Duration"
              value={banDuration}
              onChange={setBanDuration}
              options={[
                { value: '1h', label: '1 Hour' },
                { value: '24h', label: '24 Hours' },
                { value: '7d', label: '7 Days' },
                { value: '30d', label: '30 Days' },
              ]}
            />
          )}
          <Input label="Reason" value={banReason} onChange={(e) => setBanReason(e.target.value)} />
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setBanModal(false)}>Cancel</Button>
            <Button variant="danger" onClick={handleBan} disabled={!banReason}>Confirm Ban</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
