import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Shield, Ban, CheckCircle } from 'lucide-react';
import { Button } from '../../components/ui/Button';
import { GradientButton } from '../../components/ui/GradientButton';
import { Badge } from '../../components/ui/Badge';
import { Avatar } from '../../components/ui/Avatar';
import { Modal } from '../../components/ui/Modal';
import { api } from '../../api/client';
import { useAuth } from '../../context/AuthContext';
import type { ModerationLog } from '../../types';

interface UserDetail {
  id: string;
  email: string;
  fullName: string;
  nickname?: string;
  avatar?: string;
  phone?: string;
  location?: string;
  bio?: string;
  rating: number;
  ratingCount: number;
  role: string;
  isBanned: boolean;
  banReason?: string;
  bannedAt?: string;
  createdAt: string;
  _count: { listings: number; sentOffers: number; receivedOffers: number; reports: number };
}

export function AdminUserDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { isAdmin, isSuperAdmin } = useAuth();
  const [user, setUser] = useState<UserDetail | null>(null);
  const [logs, setLogs] = useState<ModerationLog[]>([]);
  const [showBan, setShowBan] = useState(false);
  const [showRole, setShowRole] = useState(false);
  const [banReason, setBanReason] = useState('');
  const [newRole, setNewRole] = useState('');

  useEffect(() => {
    if (!id) return;
    api.get<{ user: UserDetail; moderationLogs: ModerationLog[] }>(`/admin/users/${id}`)
      .then(({ user, moderationLogs }) => {
        setUser(user);
        setLogs(moderationLogs);
        setNewRole(user.role);
      })
      .catch(() => navigate('/admin/users'));
  }, [id, navigate]);

  const handleBan = async () => {
    if (!id || !banReason) return;
    await api.post(`/admin/users/${id}/ban`, { reason: banReason });
    setUser(prev => prev ? { ...prev, isBanned: true, banReason } : null);
    setShowBan(false);
    setBanReason('');
  };

  const handleUnban = async () => {
    if (!id) return;
    await api.post(`/admin/users/${id}/unban`);
    setUser(prev => prev ? { ...prev, isBanned: false, banReason: undefined } : null);
  };

  const handleRoleChange = async () => {
    if (!id || !newRole) return;
    await api.patch(`/admin/users/${id}/role`, { role: newRole });
    setUser(prev => prev ? { ...prev, role: newRole } : null);
    setShowRole(false);
  };

  if (!user) return <div className="text-center text-gray-400 py-12">Loading...</div>;

  return (
    <div>
      <button onClick={() => navigate('/admin/users')} className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 mb-4 cursor-pointer">
        <ArrowLeft className="w-4 h-4" /> Back to Users
      </button>

      <div className="bg-white rounded-xl border border-gray-200 p-6 mb-6">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-4">
            <Avatar name={user.fullName} src={user.avatar} size="lg" />
            <div>
              <h1 className="text-xl font-bold text-gray-900">{user.fullName}</h1>
              <p className="text-sm text-gray-500">{user.email}</p>
              <div className="flex items-center gap-2 mt-2">
                <Badge variant={user.role === 'SUPER_ADMIN' ? 'error' : user.role === 'ADMIN' ? 'warning' : user.role === 'MODERATOR' ? 'info' : 'default'} size="sm">
                  {user.role}
                </Badge>
                {user.isBanned && <Badge variant="error" size="sm">Banned</Badge>}
              </div>
            </div>
          </div>
          <div className="flex gap-2">
            {isAdmin && !user.isBanned && (
              <Button variant="danger" size="sm" onClick={() => setShowBan(true)}>
                <Ban className="w-4 h-4 mr-1" /> Ban
              </Button>
            )}
            {isAdmin && user.isBanned && (
              <Button variant="outline" size="sm" onClick={handleUnban}>
                <CheckCircle className="w-4 h-4 mr-1" /> Unban
              </Button>
            )}
            {isSuperAdmin && (
              <Button variant="outline" size="sm" onClick={() => setShowRole(true)}>
                <Shield className="w-4 h-4 mr-1" /> Change Role
              </Button>
            )}
          </div>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-6">
          <div className="text-center p-3 bg-gray-50 rounded-lg">
            <p className="text-lg font-bold">{user._count.listings}</p>
            <p className="text-xs text-gray-500">Listings</p>
          </div>
          <div className="text-center p-3 bg-gray-50 rounded-lg">
            <p className="text-lg font-bold">{user._count.sentOffers}</p>
            <p className="text-xs text-gray-500">Offers Sent</p>
          </div>
          <div className="text-center p-3 bg-gray-50 rounded-lg">
            <p className="text-lg font-bold">{user._count.receivedOffers}</p>
            <p className="text-xs text-gray-500">Offers Received</p>
          </div>
          <div className="text-center p-3 bg-gray-50 rounded-lg">
            <p className="text-lg font-bold">{user._count.reports}</p>
            <p className="text-xs text-gray-500">Reports Filed</p>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <h2 className="font-semibold text-gray-900 mb-4">Moderation History</h2>
        {logs.length === 0 ? (
          <p className="text-sm text-gray-400">No moderation history</p>
        ) : (
          <div className="space-y-3">
            {logs.map((log) => (
              <div key={log.id} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                <div className="flex-1">
                  <p className="text-sm font-medium">{log.action}</p>
                  {log.reason && <p className="text-xs text-gray-500 mt-0.5">{log.reason}</p>}
                  <p className="text-xs text-gray-400 mt-1">
                    by {log.moderator?.fullName} on {new Date(log.createdAt).toLocaleString()}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Ban Modal */}
      <Modal isOpen={showBan} onClose={() => setShowBan(false)} title="Ban User" size="sm">
        <p className="text-sm text-gray-500 mb-4">Provide a reason for banning {user.fullName}.</p>
        <textarea
          value={banReason}
          onChange={(e) => setBanReason(e.target.value)}
          rows={3}
          placeholder="Reason for ban..."
          className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none mb-4"
        />
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowBan(false)}>Cancel</Button>
          <Button variant="danger" className="flex-1" onClick={handleBan} disabled={!banReason}>Confirm Ban</Button>
        </div>
      </Modal>

      {/* Role Modal */}
      <Modal isOpen={showRole} onClose={() => setShowRole(false)} title="Change Role" size="sm">
        <div className="mb-4">
          <select
            value={newRole}
            onChange={(e) => setNewRole(e.target.value)}
            className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm focus:border-primary-400 focus:outline-none"
          >
            <option value="USER">User</option>
            <option value="MODERATOR">Moderator</option>
            <option value="ADMIN">Admin</option>
            <option value="SUPER_ADMIN">Super Admin</option>
          </select>
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowRole(false)}>Cancel</Button>
          <GradientButton className="flex-1" onClick={handleRoleChange}>Save</GradientButton>
        </div>
      </Modal>
    </div>
  );
}
