'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
  usersService,
  User,
  getErrorMessage,
  uploadService,
  agentTypesService,
  AgentType,
  VerificationStatus,
  VerificationDocument,
  VerificationHistoryEntry,
} from '@/services';

export default function UserDetailPage() {
  const router = useRouter();
  const params = useParams();
  const userId = params.id as string;

  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);

  // Agent type editing
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [selectedAgentTypeId, setSelectedAgentTypeId] = useState<string>('');
  const [isUpdatingAgentType, setIsUpdatingAgentType] = useState(false);
  const [updateSuccess, setUpdateSuccess] = useState('');

  // Verification
  const [verificationDocuments, setVerificationDocuments] = useState<VerificationDocument[]>([]);
  const [isLoadingDocuments, setIsLoadingDocuments] = useState(false);
  const [verificationNote, setVerificationNote] = useState('');
  const [isUpdatingVerification, setIsUpdatingVerification] = useState(false);
  const [verificationHistory, setVerificationHistory] = useState<VerificationHistoryEntry[]>([]);

  // Helper function to check if avatar is an S3 key
  const isS3Key = (avatar: string | null | undefined): boolean => {
    if (!avatar) return false;
    return !avatar.startsWith('http') && !avatar.startsWith('/');
  };

  useEffect(() => {
    fetchUser();
    fetchAgentTypes();
  }, [userId]);

  // Fetch verification documents when user is loaded and is an agent
  useEffect(() => {
    if (user && user.role === 'AGENT') {
      fetchVerificationDocuments();
      fetchVerificationHistory();
    }
  }, [user?.id, user?.role]);

  const fetchUser = async () => {
    setIsLoading(true);
    setError('');
    try {
      const userData = await usersService.getUserById(userId);
      setUser(userData);

      // Set initial agent type
      if (userData.agentProfile?.agentTypeId) {
        setSelectedAgentTypeId(userData.agentProfile.agentTypeId);
      }

      // Fetch avatar URL if needed
      const avatar = userData.profile?.avatar;
      if (avatar) {
        if (isS3Key(avatar)) {
          try {
            const presignedUrl = await uploadService.getPresignedDownloadUrl(avatar);
            setAvatarUrl(presignedUrl);
          } catch (err) {
            console.error('Failed to get avatar URL:', err);
          }
        } else {
          setAvatarUrl(avatar);
        }
      }
    } catch (err) {
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
      if (errorMessage.includes('Unauthorized')) {
        router.push('/login');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const fetchAgentTypes = async () => {
    try {
      const types = await agentTypesService.getAll();
      setAgentTypes(types);
    } catch (err) {
      console.error('Failed to fetch agent types:', err);
    }
  };

  const fetchVerificationDocuments = async () => {
    if (!user || user.role !== 'AGENT') return;

    setIsLoadingDocuments(true);
    try {
      const docs = await usersService.getVerificationDocuments(userId);
      // Fetch presigned URLs for each document
      const docsWithUrls = await Promise.all(
        docs.map(async (doc) => {
          try {
            // The S3 key is stored in 'id' field from the upload service
            // or in 'key' field if explicitly set. Fall back to id if key is missing.
            const fileKey = doc.key || doc.id;
            if (!fileKey || fileKey.startsWith('http')) {
              // If no key or already a URL, return document as-is
              return doc;
            }
            const url = await uploadService.getPresignedDownloadUrl(fileKey);
            return { ...doc, url };
          } catch {
            return doc;
          }
        })
      );
      setVerificationDocuments(docsWithUrls);
    } catch (err) {
      console.error('Failed to fetch verification documents:', err);
    } finally {
      setIsLoadingDocuments(false);
    }
  };

  const fetchVerificationHistory = async () => {
    try {
      const history = await usersService.getVerificationHistory(userId);
      setVerificationHistory(history);
    } catch {
      // History may not exist yet
    }
  };

  const handleVerification = async (status: VerificationStatus) => {
    if (!user) return;

    setIsUpdatingVerification(true);
    setError('');
    setUpdateSuccess('');

    try {
      await usersService.updateVerification(user.id, {
        status,
        note: verificationNote || undefined,
      });
      setUpdateSuccess(
        status === 'APPROVED'
          ? 'Agent verification approved successfully'
          : 'Agent verification rejected'
      );
      setVerificationNote('');
      // Refresh user data and history
      await fetchUser();
      await fetchVerificationHistory();
      // Clear success message after 3 seconds
      setTimeout(() => setUpdateSuccess(''), 3000);
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setIsUpdatingVerification(false);
    }
  };

  const getVerificationStatusBadge = (status: VerificationStatus | undefined) => {
    switch (status) {
      case 'APPROVED':
        return (
          <span className="px-3 py-1 text-sm font-semibold rounded-full bg-green-100 text-green-800">
            Approved
          </span>
        );
      case 'REJECTED':
        return (
          <span className="px-3 py-1 text-sm font-semibold rounded-full bg-red-100 text-red-800">
            Rejected
          </span>
        );
      case 'PENDING_REVIEW':
        return (
          <span className="px-3 py-1 text-sm font-semibold rounded-full bg-yellow-100 text-yellow-800">
            Pending Review
          </span>
        );
      default:
        return (
          <span className="px-3 py-1 text-sm font-semibold rounded-full bg-gray-100 text-gray-800">
            Not Submitted
          </span>
        );
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const handleUpdateAgentType = async () => {
    if (!selectedAgentTypeId || !user) return;

    setIsUpdatingAgentType(true);
    setError('');
    setUpdateSuccess('');

    try {
      await usersService.updateAgentType(user.id, selectedAgentTypeId);
      setUpdateSuccess('Agent type updated successfully');

      // Refresh user data
      await fetchUser();

      // Clear success message after 3 seconds
      setTimeout(() => setUpdateSuccess(''), 3000);
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setIsUpdatingAgentType(false);
    }
  };

  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return 'N/A';
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#f5a623]"></div>
      </div>
    );
  }

  if (error && !user) {
    return (
      <div className="p-6">
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-700">{error}</p>
        </div>
        <button
          onClick={() => router.push('/dashboard/users')}
          className="mt-4 px-4 py-2 text-[#f5a623] hover:text-[#e09620]"
        >
          ← Back to Users
        </button>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="p-6">
        <p className="text-[#666666] font-serif">User not found</p>
        <button
          onClick={() => router.push('/dashboard/users')}
          className="mt-4 px-4 py-2 text-[#f5a623] hover:text-[#e09620]"
        >
          ← Back to Users
        </button>
      </div>
    );
  }

  return (
    <div>
      {/* Back Button */}
      <button
        onClick={() => router.push('/dashboard/users')}
        className="mb-6 flex items-center text-[#666666] hover:text-[#00293d]"
      >
        <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Back to Users
      </button>

      {/* Error/Success Messages */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-700 text-sm">{error}</p>
        </div>
      )}
      {updateSuccess && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
          <p className="text-green-700 text-sm">{updateSuccess}</p>
        </div>
      )}

      {/* User Header */}
      <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb] mb-6">
        <div className="p-6">
          <div className="flex items-center">
            {/* Avatar */}
            <div className="flex-shrink-0 h-20 w-20">
              <div className="h-20 w-20 rounded-full bg-[#e8f0ee] flex items-center justify-center relative overflow-hidden">
                <span className="text-[#666666] font-medium text-2xl">
                  {user.profile?.firstName?.[0] || user.email[0].toUpperCase()}
                </span>
                {avatarUrl && (
                  <img className="absolute inset-0 h-20 w-20 rounded-full object-cover" src={avatarUrl} alt="" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                )}
              </div>
            </div>

            {/* Name & Email */}
            <div className="ml-6 flex-1">
              <h1 className="text-2xl font-bold text-[#00293d] font-fractul">
                {user.profile?.firstName} {user.profile?.lastName}
              </h1>
              <p className="text-[#666666] font-serif">{user.email}</p>
            </div>

            {/* Role & Status Badges */}
            <div className="flex items-center space-x-3">
              <span
                className={`px-3 py-1 text-sm font-semibold rounded-full ${
                  user.role === 'ADMIN'
                    ? 'bg-red-100 text-red-800'
                    : user.role === 'AGENT'
                    ? 'bg-[#fff7ed] text-[#f5a623]'
                    : 'bg-[#e8f0ee] text-[#5ba4a4]'
                }`}
              >
                {user.role}
              </span>
              <span
                className={`px-3 py-1 text-sm font-semibold rounded-full ${
                  user.status === 'ACTIVE'
                    ? 'bg-green-100 text-green-800'
                    : user.status === 'SUSPENDED'
                    ? 'bg-red-100 text-red-800'
                    : 'bg-yellow-100 text-yellow-800'
                }`}
              >
                {user.status}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Basic Information */}
      <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb] mb-6">
        <div className="px-6 py-4 border-b border-[#e5e7eb]">
          <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Basic Information</h2>
        </div>
        <div className="p-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div>
              <p className="text-sm text-[#666666]">Provider</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.authProvider === 'LOCAL' ? 'Email' : user.authProvider}
              </p>
            </div>
            <div>
              <p className="text-sm text-[#666666]">Email Verified</p>
              <div className="flex items-center">
                {user.emailVerified ? (
                  <>
                    <svg className="w-5 h-5 text-green-500 mr-1" fill="currentColor" viewBox="0 0 20 20">
                      <path
                        fillRule="evenodd"
                        d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                        clipRule="evenodd"
                      />
                    </svg>
                    <span className="text-sm font-medium text-green-600">Verified</span>
                  </>
                ) : (
                  <>
                    <svg className="w-5 h-5 text-[#9ca3af] mr-1" fill="currentColor" viewBox="0 0 20 20">
                      <path
                        fillRule="evenodd"
                        d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                        clipRule="evenodd"
                      />
                    </svg>
                    <span className="text-sm font-medium text-[#666666]">Not Verified</span>
                  </>
                )}
              </div>
            </div>
            <div>
              <p className="text-sm text-[#666666]">Joined</p>
              <p className="text-sm font-medium text-[#00293d]">{formatDate(user.createdAt)}</p>
            </div>
            <div>
              <p className="text-sm text-[#666666]">Last Login</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.lastLoginAt ? formatDate(user.lastLoginAt) : 'Never'}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Contact Information */}
      <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb] mb-6">
        <div className="px-6 py-4 border-b border-[#e5e7eb]">
          <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Contact Information</h2>
        </div>
        <div className="p-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div>
              <p className="text-sm text-[#666666]">Phone</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.profile?.phone || 'Not provided'}
              </p>
            </div>
            <div>
              <p className="text-sm text-[#666666]">City</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.profile?.city || 'Not provided'}
              </p>
            </div>
            <div>
              <p className="text-sm text-[#666666]">State</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.profile?.state || 'Not provided'}
              </p>
            </div>
            <div>
              <p className="text-sm text-[#666666]">Country</p>
              <p className="text-sm font-medium text-[#00293d]">
                {user.profile?.country || 'Not provided'}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Agent Details (only for AGENT role) */}
      {user.role === 'AGENT' && user.agentProfile && (
        <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb] mb-6">
          <div className="px-6 py-4 border-b border-[#e5e7eb]">
            <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Agent Details</h2>
          </div>
          <div className="p-6">
            {/* Agent Details Grid */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {/* Agent Type - Editable */}
              <div>
                <p className="text-sm text-[#666666] mb-1">Agent Type</p>
                <div className="flex items-center space-x-2">
                  <select
                    value={selectedAgentTypeId}
                    onChange={(e) => setSelectedAgentTypeId(e.target.value)}
                    className="w-full max-w-[160px] px-2 py-1 text-sm border border-[#e5e7eb] rounded-lg focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white"
                  >
                    <option value="">Select...</option>
                    {agentTypes.map((type) => (
                      <option key={type.id} value={type.id}>
                        {type.name}
                      </option>
                    ))}
                  </select>
                  {selectedAgentTypeId && selectedAgentTypeId !== user.agentProfile?.agentTypeId && (
                    <button
                      onClick={handleUpdateAgentType}
                      disabled={isUpdatingAgentType}
                      className="px-2 py-1 bg-[#f5a623] hover:bg-[#e09620] text-white text-xs font-medium rounded transition-colors disabled:opacity-50"
                    >
                      {isUpdatingAgentType ? '...' : 'Save'}
                    </button>
                  )}
                </div>
              </div>
              <div>
                <p className="text-sm text-[#666666]">Slug</p>
                <p className="text-sm font-medium text-[#00293d]">
                  {user.agentProfile.slug || 'Not set'}
                </p>
              </div>
              <div>
                <p className="text-sm text-[#666666]">Company</p>
                <p className="text-sm font-medium text-[#00293d]">
                  {user.agentProfile.companyName || 'Not provided'}
                </p>
              </div>
              <div>
                <p className="text-sm text-[#666666]">License Number</p>
                <p className="text-sm font-medium text-[#00293d]">
                  {user.agentProfile.licenseNumber || 'Not provided'}
                </p>
              </div>
              <div>
                <p className="text-sm text-[#666666]">Years of Experience</p>
                <p className="text-sm font-medium text-[#00293d]">
                  {user.agentProfile.yearsOfExperience ?? 'Not provided'}
                </p>
              </div>
              <div>
                <p className="text-sm text-[#666666]">Profile Status</p>
                <p className="text-sm font-medium text-[#00293d]">
                  {user.agentProfile.profileCompleteness}%{' '}
                  <span
                    className={`ml-1 inline-flex px-2 py-0.5 text-xs font-semibold rounded-full ${
                      user.agentProfile.isProfileComplete
                        ? 'bg-green-100 text-green-800'
                        : 'bg-yellow-100 text-yellow-800'
                    }`}
                  >
                    {user.agentProfile.isProfileComplete ? 'Complete' : 'Incomplete'}
                  </span>
                </p>
              </div>
            </div>

            {/* Headline & Bio */}
            {(user.agentProfile.headline || user.agentProfile.bio) && (
              <div className="mt-6 pt-6 border-t border-[#e5e7eb]">
                {user.agentProfile.headline && (
                  <div className="mb-4">
                    <p className="text-sm text-[#666666] mb-1">Headline</p>
                    <p className="text-sm font-medium text-[#00293d]">
                      {user.agentProfile.headline}
                    </p>
                  </div>
                )}
                {user.agentProfile.bio && (
                  <div>
                    <p className="text-sm text-[#666666] mb-1">Bio</p>
                    <p className="text-sm text-[#666666] whitespace-pre-wrap">
                      {user.agentProfile.bio}
                    </p>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Verification Section (only for AGENT role) */}
      {user.role === 'AGENT' && user.agentProfile && (
        <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb] mb-6">
          <div className="px-6 py-4 border-b border-[#e5e7eb]">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Verification Status</h2>
              {getVerificationStatusBadge(user.agentProfile.verificationStatus as VerificationStatus)}
            </div>
          </div>
          <div className="p-6">
            {/* Verification Info */}
            {user.agentProfile.isVerified && user.agentProfile.verifiedAt && (
              <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                <p className="text-green-700 text-sm">
                  Verified on {formatDate(user.agentProfile.verifiedAt)}
                </p>
              </div>
            )}

            {user.agentProfile.verificationStatus === 'REJECTED' && user.agentProfile.verificationNote && (
              <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-700 text-sm font-medium">Rejection Note:</p>
                <p className="text-red-600 text-sm mt-1">{user.agentProfile.verificationNote}</p>
              </div>
            )}

            {/* Uploaded Documents */}
            <div className="mb-6">
              <h3 className="text-sm font-medium text-[#00293d] mb-3">Uploaded Documents</h3>
              {isLoadingDocuments ? (
                <div className="flex items-center justify-center py-4">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#f5a623]"></div>
                </div>
              ) : verificationDocuments.length > 0 ? (
                <div className="space-y-2">
                  {verificationDocuments.map((doc, index) => (
                    <div
                      key={index}
                      className="flex items-center justify-between p-3 bg-[#f5f9f8] border border-[#e5e7eb] rounded-xl"
                    >
                      <div className="flex items-center">
                        <svg
                          className="w-8 h-8 text-[#9ca3af] mr-3"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                          />
                        </svg>
                        <div>
                          <p className="text-sm font-medium text-[#00293d]">{doc.name}</p>
                          <p className="text-xs text-[#666666]">{formatFileSize(doc.size)}</p>
                        </div>
                      </div>
                      {doc.url && (
                        <a
                          href={doc.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="px-3 py-1 text-sm text-[#f5a623] hover:text-[#e09620] hover:bg-[#fff7ed] rounded transition-colors"
                        >
                          Download
                        </a>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-[#666666] py-4 text-center">
                  No documents uploaded yet
                </p>
              )}
            </div>

            {/* Admin Actions */}
            {user.agentProfile.verificationStatus !== 'APPROVED' && (
              <div className="border-t border-[#e5e7eb] pt-6">
                <h3 className="text-sm font-medium text-[#00293d] mb-3">Admin Actions</h3>

                {/* Note Input */}
                <div className="mb-4">
                  <label className="block text-sm text-[#666666] mb-1">
                    Note (optional, required for rejection)
                  </label>
                  <textarea
                    value={verificationNote}
                    onChange={(e) => setVerificationNote(e.target.value)}
                    rows={2}
                    className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white placeholder:text-[#666666]"
                    placeholder="Enter a note for the agent (e.g., rejection reason)"
                  />
                </div>

                {/* Action Buttons */}
                <div className="flex space-x-3">
                  <button
                    onClick={() => handleVerification('APPROVED')}
                    disabled={isUpdatingVerification || verificationDocuments.length === 0}
                    className="flex-1 px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isUpdatingVerification ? (
                      <span className="flex items-center justify-center">
                        <svg
                          className="animate-spin -ml-1 mr-2 h-4 w-4"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          />
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          />
                        </svg>
                        Processing...
                      </span>
                    ) : (
                      <>
                        <svg
                          className="w-4 h-4 inline mr-1"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M5 13l4 4L19 7"
                          />
                        </svg>
                        Approve Verification
                      </>
                    )}
                  </button>
                  <button
                    onClick={() => handleVerification('REJECTED')}
                    disabled={isUpdatingVerification || !verificationNote.trim()}
                    className="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isUpdatingVerification ? (
                      <span className="flex items-center justify-center">
                        <svg
                          className="animate-spin -ml-1 mr-2 h-4 w-4"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          />
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          />
                        </svg>
                        Processing...
                      </span>
                    ) : (
                      <>
                        <svg
                          className="w-4 h-4 inline mr-1"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M6 18L18 6M6 6l12 12"
                          />
                        </svg>
                        Reject Verification
                      </>
                    )}
                  </button>
                </div>
                {!verificationNote.trim() && (
                  <p className="mt-2 text-xs text-[#666666]">
                    * A note is required to reject verification
                  </p>
                )}
                {verificationDocuments.length === 0 && (
                  <p className="mt-2 text-xs text-amber-600">
                    * Cannot approve without uploaded documents
                  </p>
                )}
              </div>
            )}

            {/* Already Approved Message */}
            {user.agentProfile.verificationStatus === 'APPROVED' && (
              <div className="border-t border-[#e5e7eb] pt-6">
                <div className="flex items-center text-green-600">
                  <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path
                      fillRule="evenodd"
                      d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                      clipRule="evenodd"
                    />
                  </svg>
                  <span className="font-medium">This agent is verified</span>
                </div>
              </div>
            )}

            {/* Verification History */}
            {verificationHistory.length > 0 && (
              <div className="border-t border-[#e5e7eb] pt-6">
                <h3 className="text-sm font-medium text-[#00293d] mb-3">Verification History</h3>
                <div className="space-y-3">
                  {verificationHistory.map((entry) => (
                    <div key={entry.id} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                      <div className={`w-2 h-2 rounded-full mt-1.5 flex-shrink-0 ${
                        entry.status === 'APPROVED' ? 'bg-green-500' :
                        entry.status === 'REJECTED' ? 'bg-red-500' :
                        entry.status === 'PENDING_REVIEW' ? 'bg-yellow-500' : 'bg-gray-400'
                      }`} />
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className={`px-2 py-0.5 text-xs font-semibold rounded-full ${
                            entry.status === 'APPROVED' ? 'bg-green-100 text-green-800' :
                            entry.status === 'REJECTED' ? 'bg-red-100 text-red-800' :
                            entry.status === 'PENDING_REVIEW' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800'
                          }`}>
                            {entry.status.replace('_', ' ')}
                          </span>
                          <span className="text-xs text-gray-500">
                            {new Date(entry.createdAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                          </span>
                        </div>
                        {entry.note && (
                          <p className="text-sm text-gray-700 mt-1">{entry.note}</p>
                        )}
                        {entry.admin && (
                          <p className="text-xs text-gray-500 mt-1">By: {entry.admin.email}</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
