'use client';

import AdminShell from '@/components/AdminShell';
import { api } from '@/lib/api';
import { statusColor, formatDateTime } from '@/lib/utils';
import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, Shield, Ban, CheckCircle, XCircle, Star, RotateCcw } from 'lucide-react';
import Link from 'next/link';

export default function UserDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [showModal, setShowModal] = useState<string | null>(null);
  const [reason, setReason] = useState('');

  const fetchUser = () => {
    setLoading(true);
    api.getUser(params.id as string)
      .then(setUser)
      .catch(() => router.push('/users'))
      .finally(() => setLoading(false));
  };

  useEffect(() => { fetchUser(); }, [params.id]);

  const handleStatusChange = async (status: string) => {
    if (!reason.trim()) return;
    setActionLoading(true);
    try {
      await api.updateUserStatus(params.id as string, status, reason);
      setShowModal(null);
      setReason('');
      fetchUser();
    } catch (e: any) {
      alert(`Status change failed: ${e.message}`);
    }
    setActionLoading(false);
  };

  const handleRoleChange = async (role: string) => {
    setActionLoading(true);
    try {
      await api.updateUserRole(params.id as string, role);
      fetchUser();
    } catch (e: any) {
      alert(`Role change failed: ${e.message}`);
    }
    setActionLoading(false);
  };

  const handleVerification = async (isOfficial: boolean, isVerified: boolean) => {
    setActionLoading(true);
    try {
      await api.updateUserVerification(params.id as string, isOfficial, isVerified);
      fetchUser();
    } catch (e: any) {
      alert(`Verification update failed: ${e.message}`);
    }
    setActionLoading(false);
  };

  const handleResetStrikes = async () => {
    setActionLoading(true);
    try {
      await api.resetUserStrikes(params.id as string);
      fetchUser();
    } catch (e: any) {
      alert(`Reset strikes failed: ${e.message}`);
    }
    setActionLoading(false);
  };

  return (
    <AdminShell>
      <Link href="/users" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
        <ArrowLeft className="w-4 h-4" /> Back to Users
      </Link>

      {loading ? (
        <div className="card p-8 animate-pulse"><div className="h-6 bg-warm-300 rounded w-40" /></div>
      ) : user ? (
        <div className="space-y-6">
          {/* Header */}
          <div className="card p-6">
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 bg-brand-100 rounded-2xl flex items-center justify-center text-brand-600 text-xl font-bold">
                  {(user.handle || user.email || '?')[0].toUpperCase()}
                </div>
                <div>
                  <h1 className="text-xl font-bold text-gray-900">{user.display_name || user.handle || '—'}</h1>
                  <p className="text-sm text-gray-500">@{user.handle || '—'} · {user.email}</p>
                  <div className="flex items-center gap-2 mt-2">
                    <span className={`badge ${statusColor(user.status)}`}>{user.status}</span>
                    <span className={`badge ${user.role === 'admin' ? 'bg-purple-100 text-purple-700' : user.role === 'moderator' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>
                      {user.role || 'user'}
                    </span>
                    {user.is_official && <span className="badge bg-blue-100 text-blue-700">Official</span>}
                    {user.is_verified && <span className="badge bg-green-100 text-green-700">Verified</span>}
                    {user.is_private && <span className="badge bg-gray-100 text-gray-600">Private</span>}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Stats Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
            {[
              { label: 'Followers', value: user.follower_count },
              { label: 'Following', value: user.following_count },
              { label: 'Posts', value: user.post_count },
              { label: 'Strikes', value: user.strikes },
              { label: 'Violations', value: user.violation_count },
              { label: 'Reports', value: user.report_count },
            ].map((s) => (
              <div key={s.label} className="card p-4 text-center">
                <p className="text-2xl font-bold text-gray-900">{s.value ?? 0}</p>
                <p className="text-xs text-gray-500 mt-1">{s.label}</p>
              </div>
            ))}
          </div>

          {/* Details */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="card p-5">
              <h3 className="text-sm font-semibold text-gray-700 mb-3">Profile Details</h3>
              <dl className="space-y-2 text-sm">
                {[
                  ['Bio', user.bio],
                  ['Location', user.location],
                  ['Website', user.website],
                  ['Country', user.origin_country],
                  ['Beacon Enabled', user.beacon_enabled ? 'Yes' : 'No'],
                  ['Onboarding Complete', user.has_completed_onboarding ? 'Yes' : 'No'],
                  ['Joined', user.created_at ? formatDateTime(user.created_at) : '—'],
                  ['Last Login', user.last_login ? formatDateTime(user.last_login) : 'Never'],
                ].map(([label, value]) => (
                  <div key={label as string} className="flex justify-between">
                    <dt className="text-gray-500">{label}</dt>
                    <dd className="text-gray-900 font-medium text-right max-w-xs truncate">{value || '—'}</dd>
                  </div>
                ))}
              </dl>
            </div>

            {/* Actions */}
            <div className="card p-5">
              <h3 className="text-sm font-semibold text-gray-700 mb-3">Admin Actions</h3>
              <div className="space-y-3">
                {/* Status changes */}
                <div>
                  <p className="text-xs font-medium text-gray-500 mb-2">Account Status</p>
                  <div className="flex flex-wrap gap-2">
                    {user.status !== 'active' && (
                      <button onClick={() => setShowModal('active')} className="btn-primary text-xs py-1.5 flex items-center gap-1">
                        <CheckCircle className="w-3.5 h-3.5" /> Activate
                      </button>
                    )}
                    {user.status !== 'suspended' && (
                      <button onClick={() => setShowModal('suspended')} className="bg-orange-500 text-white px-3 py-1.5 rounded-lg text-xs font-medium hover:bg-orange-600 flex items-center gap-1">
                        <XCircle className="w-3.5 h-3.5" /> Suspend
                      </button>
                    )}
                    {user.status !== 'banned' && (
                      <button onClick={() => setShowModal('banned')} className="btn-danger text-xs py-1.5 flex items-center gap-1">
                        <Ban className="w-3.5 h-3.5" /> Ban
                      </button>
                    )}
                  </div>
                </div>

                {/* Role */}
                <div>
                  <p className="text-xs font-medium text-gray-500 mb-2">Role</p>
                  <select
                    className="input text-sm"
                    value={user.role || 'user'}
                    onChange={(e) => handleRoleChange(e.target.value)}
                    disabled={actionLoading}
                  >
                    <option value="user">User</option>
                    <option value="moderator">Moderator</option>
                    <option value="admin">Admin</option>
                  </select>
                </div>

                {/* Verification */}
                <div>
                  <p className="text-xs font-medium text-gray-500 mb-2">Verification</p>
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleVerification(!user.is_official, user.is_verified ?? false)}
                      className={`text-xs py-1.5 px-3 rounded-lg font-medium flex items-center gap-1 ${user.is_official ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                      disabled={actionLoading}
                    >
                      <Star className="w-3.5 h-3.5" /> {user.is_official ? 'Remove Official' : 'Make Official'}
                    </button>
                    <button
                      onClick={() => handleVerification(user.is_official ?? false, !user.is_verified)}
                      className={`text-xs py-1.5 px-3 rounded-lg font-medium flex items-center gap-1 ${user.is_verified ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                      disabled={actionLoading}
                    >
                      <CheckCircle className="w-3.5 h-3.5" /> {user.is_verified ? 'Unverify' : 'Verify'}
                    </button>
                  </div>
                </div>

                {/* Reset Strikes */}
                {(user.strikes ?? 0) > 0 && (
                  <div>
                    <p className="text-xs font-medium text-gray-500 mb-2">Strikes</p>
                    <button onClick={handleResetStrikes} className="btn-secondary text-xs py-1.5 flex items-center gap-1" disabled={actionLoading}>
                      <RotateCcw className="w-3.5 h-3.5" /> Reset Strikes ({user.strikes})
                    </button>
                  </div>
                )}

                {/* View Posts */}
                <div className="pt-2 border-t border-warm-300">
                  <Link href={`/posts?author_id=${user.id}`} className="text-brand-500 hover:text-brand-700 text-sm font-medium">
                    View User&apos;s Posts →
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="card p-8 text-center text-gray-500">User not found</div>
      )}

      {/* Status Change Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={() => setShowModal(null)}>
          <div className="card p-6 w-full max-w-md mx-4" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-semibold text-gray-900 mb-1">
              {showModal === 'active' ? 'Activate' : showModal === 'suspended' ? 'Suspend' : 'Ban'} User
            </h3>
            <p className="text-sm text-gray-500 mb-4">Please provide a reason for this action.</p>
            <textarea
              className="input mb-4"
              rows={3}
              placeholder="Reason..."
              value={reason}
              onChange={(e) => setReason(e.target.value)}
            />
            <div className="flex gap-2 justify-end">
              <button onClick={() => setShowModal(null)} className="btn-secondary text-sm">Cancel</button>
              <button
                onClick={() => handleStatusChange(showModal)}
                className={showModal === 'banned' ? 'btn-danger text-sm' : 'btn-primary text-sm'}
                disabled={actionLoading || !reason.trim()}
              >
                {actionLoading ? 'Processing...' : 'Confirm'}
              </button>
            </div>
          </div>
        </div>
      )}
    </AdminShell>
  );
}
