import React, { useEffect, useState } from 'react';
import api from '@/lib/api';

interface QRCode {
  id: string;
  name: string;
  type: string;
  data_type: string;
  destination_url: string;
  short_url_id: string;
  created_at: string;
  scan_count: string;
}

interface UserDetails {
  user: {
    id: string;
    email: string;
    role: string;
    created_at: string;
  };
  qrCodes: QRCode[];
}

interface UserDetailsModalProps {
  userId: string;
  onClose: () => void;
}

export default function UserDetailsModal({ userId, onClose }: UserDetailsModalProps) {
  const [details, setDetails] = useState<UserDetails | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDetails = async () => {
      try {
        const res = await api.get(`/admin/users/${userId}/details`);
        setDetails(res.data);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    fetchDetails();
  }, [userId]);

  if (!userId) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/50 backdrop-blur-sm">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex justify-between items-center p-6 border-b border-gray-100 bg-gray-50">
          <h2 className="text-xl font-bold text-gray-900">User Details</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition-colors">
            <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
          </button>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto flex-1">
          {loading ? (
            <div className="text-center text-gray-500 py-10">Loading details...</div>
          ) : details ? (
            <div className="space-y-8">
              {/* User Info Overview */}
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-full bg-indigo-100 text-indigo-700 flex items-center justify-center text-xl font-bold">
                  {details.user.email.charAt(0).toUpperCase()}
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">{details.user.email}</h3>
                  <div className="flex gap-3 text-sm text-gray-500 mt-1">
                    <span className="uppercase font-semibold tracking-wider text-indigo-600">{details.user.role.replace('_', ' ')}</span>
                    <span>&bull;</span>
                    <span>Joined: {new Date(details.user.created_at).toLocaleDateString()}</span>
                    <span>&bull;</span>
                    <span>Total QRs: {details.qrCodes.length}</span>
                  </div>
                </div>
              </div>

              {/* QR Codes List */}
              <div>
                <h4 className="text-base font-bold text-gray-900 mb-4 border-b pb-2">Active QR Codes</h4>
                {details.qrCodes.length === 0 ? (
                  <p className="text-gray-500 text-sm">This user has not created any QR codes yet.</p>
                ) : (
                  <div className="grid grid-cols-1 gap-4">
                    {details.qrCodes.map(qr => (
                      <div key={qr.id} className="bg-gray-50 rounded-xl p-4 border border-gray-100 flex justify-between items-center hover:bg-gray-100 transition-colors">
                        <div>
                          <div className="font-bold text-gray-900 flex items-center gap-2">
                            {qr.name || 'Untitled QR'}
                            <span className="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700">
                              {qr.type}
                            </span>
                          </div>
                          <div className="text-xs text-gray-500 mt-1 truncate max-w-md" title={qr.destination_url}>
                            <a href={qr.destination_url} target="_blank" rel="noopener noreferrer" className="hover:text-indigo-600 hover:underline">
                              {qr.destination_url}
                            </a>
                          </div>
                          {qr.type === 'dynamic' && qr.short_url_id && (
                            <div className="text-xs text-indigo-500 mt-1">
                              <a href={`${process.env.NEXT_PUBLIC_APP_URL || ''}/l/${qr.short_url_id}`} target="_blank" rel="noopener noreferrer" className="hover:text-indigo-700 hover:underline">
                                /{qr.short_url_id}
                              </a>
                            </div>
                          )}
                        </div>
                        <div className="text-right">
                          <div className="text-2xl font-black text-gray-900">{qr.scan_count || 0}</div>
                          <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Scans</div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div className="text-center text-red-500 py-10">Failed to load details.</div>
          )}
        </div>
      </div>
    </div>
  );
}
