"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/hooks/useAuth";
import Layout from "@/app/components/Layout";
import {
  CheckCircle,
  XCircle,
  Clock,
  Eye,
  Search,
  Filter,
} from "lucide-react";

interface User {
  id: number;
  name: string;
  email: string;
  phone: string | null;
  ownerName: string | null;
  shopName: string | null;
  city: string | null;
  profileCompleted: boolean;
  profileVerificationStatus: 'pending' | 'verified' | 'rejected';
  shopImages: string[] | null;
  selfieImage: string | null;
  shopactDocument: string | null;
  udyamAadharDocument: string | null;
  gstDocument: string | null;
  aadharCardImage: string | null;
  panCardImage: string | null;
  createdAt: string;
}

export default function VerificationRequestsPage() {
  const { user, isAuthenticated } = useAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [filter, setFilter] = useState<'all' | 'pending' | 'verified' | 'rejected'>('pending');
  const [searchTerm, setSearchTerm] = useState('');
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  useEffect(() => {
    if (isAuthenticated) {
      fetchVerificationRequests();
    }
  }, [isAuthenticated, filter]);

  const fetchVerificationRequests = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem("token");
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}/api/admin/users?verificationStatus=${filter}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (response.ok) {
        const data = await response.json();
        setUsers(data.data || []);
      }
    } catch (error) {
      console.error("Error fetching verification requests:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async (userId: number, status: 'verified' | 'rejected') => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}/api/admin/users/${userId}/verify`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({ status }),
        }
      );

      if (response.ok) {
        await fetchVerificationRequests();
        setSelectedUser(null);
        alert(`User profile ${status === 'verified' ? 'verified' : 'rejected'} successfully`);
      } else {
        const error = await response.json();
        alert(error.message || "Failed to update verification status");
      }
    } catch (error) {
      console.error("Error updating verification status:", error);
      alert("Failed to update verification status");
    }
  };

  const filteredUsers = users.filter((u) => {
    const matchesSearch =
      u.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.phone?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.shopName?.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesSearch;
  });

  const showContent = isMounted && isAuthenticated;

  if (!showContent) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            CRM Verification Requests
          </h1>
          <p className="text-xl text-gray-600 mb-8">Please login to continue</p>
        </div>
      </div>
    );
  }

  return (
    <Layout>
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="mb-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              User Verification Requests
            </h1>
            <p className="text-gray-600">
              Review and verify user profile submissions
            </p>
          </div>

          {/* Filters and Search */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
            <div className="flex flex-col md:flex-row gap-4">
              {/* Search */}
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="Search by name, email, phone, or shop name..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>

              {/* Filter Buttons */}
              <div className="flex gap-2">
                <button
                  onClick={() => setFilter('all')}
                  className={`px-4 py-2 rounded-lg font-medium transition-colors ${filter === 'all'
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                >
                  All
                </button>
                <button
                  onClick={() => setFilter('pending')}
                  className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${filter === 'pending'
                      ? 'bg-yellow-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                >
                  <Clock className="w-4 h-4" />
                  Pending
                </button>
                <button
                  onClick={() => setFilter('verified')}
                  className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${filter === 'verified'
                      ? 'bg-green-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                >
                  <CheckCircle className="w-4 h-4" />
                  Verified
                </button>
                <button
                  onClick={() => setFilter('rejected')}
                  className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${filter === 'rejected'
                      ? 'bg-red-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                >
                  <XCircle className="w-4 h-4" />
                  Rejected
                </button>
              </div>
            </div>
          </div>

          {/* Users Table */}
          {loading ? (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
              <div className="inline-block w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
              <p className="mt-4 text-gray-600">Loading verification requests...</p>
            </div>
          ) : filteredUsers.length === 0 ? (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
              <p className="text-gray-600">No verification requests found</p>
            </div>
          ) : (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        User
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Shop Details
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Submitted
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {filteredUsers.map((user) => (
                      <tr key={user.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div>
                            <div className="text-sm font-medium text-gray-900">
                              {user.name}
                            </div>
                            <div className="text-sm text-gray-500">{user.email}</div>
                            {user.phone && (
                              <div className="text-sm text-gray-500">{user.phone}</div>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <div className="text-sm text-gray-900">
                            {user.shopName || "N/A"}
                          </div>
                          {user.city && (
                            <div className="text-sm text-gray-500">{user.city}</div>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {user.profileVerificationStatus === 'pending' && (
                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                              <Clock className="w-3 h-3" />
                              Pending
                            </span>
                          )}
                          {user.profileVerificationStatus === 'verified' && (
                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                              <CheckCircle className="w-3 h-3" />
                              Verified
                            </span>
                          )}
                          {user.profileVerificationStatus === 'rejected' && (
                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                              <XCircle className="w-3 h-3" />
                              Rejected
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {new Date(user.createdAt).toLocaleDateString()}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                          <button
                            onClick={() => setSelectedUser(user)}
                            className="text-blue-600 hover:text-blue-900 mr-4 flex items-center gap-1"
                          >
                            <Eye className="w-4 h-4" />
                            View
                          </button>
                          {user.profileVerificationStatus === 'pending' && (
                            <>
                              <button
                                onClick={() => handleVerify(user.id, 'verified')}
                                className="text-green-600 hover:text-green-900 mr-4"
                              >
                                Verify
                              </button>
                              <button
                                onClick={() => handleVerify(user.id, 'rejected')}
                                className="text-red-600 hover:text-red-900"
                              >
                                Reject
                              </button>
                            </>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* User Details Modal */}
          {selectedUser && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div className="p-6 border-b border-gray-200 flex justify-between items-center">
                  <h2 className="text-2xl font-bold text-gray-900">
                    User Verification Details
                  </h2>
                  <button
                    onClick={() => setSelectedUser(null)}
                    className="text-gray-400 hover:text-gray-600"
                  >
                    <XCircle className="w-6 h-6" />
                  </button>
                </div>

                <div className="p-6 space-y-6">
                  {/* Basic Info */}
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">
                      Basic Information
                    </h3>
                    <div className="grid md:grid-cols-2 gap-4">
                      <div>
                        <label className="text-sm font-medium text-gray-500">Name</label>
                        <p className="text-gray-900">{selectedUser.name}</p>
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-500">Email</label>
                        <p className="text-gray-900">{selectedUser.email}</p>
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-500">Phone</label>
                        <p className="text-gray-900">{selectedUser.phone || "N/A"}</p>
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-500">Owner Name</label>
                        <p className="text-gray-900">{selectedUser.ownerName || "N/A"}</p>
                      </div>
                    </div>
                  </div>

                  {/* Shop Details */}
                  {selectedUser.shopName && (
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900 mb-4">
                        Shop Details
                      </h3>
                      <div className="grid md:grid-cols-2 gap-4">
                        <div>
                          <label className="text-sm font-medium text-gray-500">Shop Name</label>
                          <p className="text-gray-900">{selectedUser.shopName}</p>
                        </div>
                        {selectedUser.city && (
                          <div>
                            <label className="text-sm font-medium text-gray-500">City</label>
                            <p className="text-gray-900">{selectedUser.city}</p>
                          </div>
                        )}
                      </div>
                    </div>
                  )}

                  {/* Images */}
                  {(selectedUser.shopImages?.length || selectedUser.selfieImage) && (
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900 mb-4">
                        Images
                      </h3>
                      <div className="grid md:grid-cols-3 gap-4">
                        {selectedUser.shopImages?.map((img, idx) => (
                          <div key={idx} className="relative aspect-video rounded-lg overflow-hidden border border-gray-200">
                            <img
                              src={img.startsWith('http') ? img : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${img}`}
                              alt={`Shop ${idx + 1}`}
                              className="w-full h-full object-cover"
                            />
                          </div>
                        ))}
                        {selectedUser.selfieImage && (
                          <div className="relative aspect-video rounded-lg overflow-hidden border border-gray-200">
                            <img
                              src={selectedUser.selfieImage.startsWith('http') ? selectedUser.selfieImage : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.selfieImage}`}
                              alt="Selfie"
                              className="w-full h-full object-cover"
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  )}

                  {/* Documents */}
                  {(selectedUser.shopactDocument ||
                    selectedUser.udyamAadharDocument ||
                    selectedUser.gstDocument ||
                    selectedUser.aadharCardImage ||
                    selectedUser.panCardImage) && (
                      <div>
                        <h3 className="text-lg font-semibold text-gray-900 mb-4">
                          Documents
                        </h3>
                        <div className="grid md:grid-cols-2 gap-4">
                          {selectedUser.shopactDocument && (
                            <div>
                              <label className="text-sm font-medium text-gray-500">Shopact</label>
                              <a
                                href={selectedUser.shopactDocument.startsWith('http') ? selectedUser.shopactDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.shopactDocument}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline block mt-1"
                              >
                                View Document
                              </a>
                            </div>
                          )}
                          {selectedUser.udyamAadharDocument && (
                            <div>
                              <label className="text-sm font-medium text-gray-500">Udyam Aadhar</label>
                              <a
                                href={selectedUser.udyamAadharDocument.startsWith('http') ? selectedUser.udyamAadharDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.udyamAadharDocument}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline block mt-1"
                              >
                                View Document
                              </a>
                            </div>
                          )}
                          {selectedUser.gstDocument && (
                            <div>
                              <label className="text-sm font-medium text-gray-500">GST</label>
                              <a
                                href={selectedUser.gstDocument.startsWith('http') ? selectedUser.gstDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.gstDocument}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline block mt-1"
                              >
                                View Document
                              </a>
                            </div>
                          )}
                          {selectedUser.aadharCardImage && (
                            <div>
                              <label className="text-sm font-medium text-gray-500">Aadhar Card</label>
                              <div className="mt-2 relative aspect-video rounded-lg overflow-hidden border border-gray-200">
                                <img
                                  src={selectedUser.aadharCardImage.startsWith('http') ? selectedUser.aadharCardImage : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.aadharCardImage}`}
                                  alt="Aadhar Card"
                                  className="w-full h-full object-cover"
                                />
                              </div>
                            </div>
                          )}
                          {selectedUser.panCardImage && (
                            <div>
                              <label className="text-sm font-medium text-gray-500">Pan Card</label>
                              <div className="mt-2 relative aspect-video rounded-lg overflow-hidden border border-gray-200">
                                <img
                                  src={selectedUser.panCardImage.startsWith('http') ? selectedUser.panCardImage : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${selectedUser.panCardImage}`}
                                  alt="Pan Card"
                                  className="w-full h-full object-cover"
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    )}

                  {/* Actions */}
                  {selectedUser.profileVerificationStatus === 'pending' && (
                    <div className="flex gap-4 pt-4 border-t border-gray-200">
                      <button
                        onClick={() => {
                          handleVerify(selectedUser.id, 'verified');
                          setSelectedUser(null);
                        }}
                        className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center justify-center gap-2"
                      >
                        <CheckCircle className="w-5 h-5" />
                        Verify Profile
                      </button>
                      <button
                        onClick={() => {
                          handleVerify(selectedUser.id, 'rejected');
                          setSelectedUser(null);
                        }}
                        className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2"
                      >
                        <XCircle className="w-5 h-5" />
                        Reject Profile
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
}
