import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Search, MapPin, ChevronDown, SlidersHorizontal, User } from 'lucide-react';

export default function MatrimonyPage() {
  const [profiles, setProfiles] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Search filters
  const [searchFilters, setSearchFilters] = useState({
    gender: '',
    location: '',
    searchText: '',
    minAge: '',
    maxAge: '',
    religion: '',
    maritalStatus: '',
    education: '',
    profession: '',
    minHeight: '',
    maxHeight: '',
    sortBy: 'newest'
  });

  //dummy profiles
  const dummyProfiles = [
    {
      id: "1",
      createdAt: "2026-01-10T14:30:00Z",
      name: "Sarah Ahmed",
      age: 28,
      city: "New York",
      gender: "Female",
      religion: "Islam",
      maritalStatus: "Never Married",
      education: "Master's Degree",
      profession: "Software Engineer",
      height: "5'6\"",
      image: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=500&q=80"
    },
    {
      id: "2",
      createdAt: "2026-01-09T10:15:00Z",
      name: "Michael Chen",
      age: 32,
      city: "Los Angeles",
      gender: "Male",
      religion: "Christian",
      maritalStatus: "Never Married",
      education: "Bachelor's Degree",
      profession: "Business Analyst",
      height: "5'10\"",
      image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500&q=80"
    },
    {
      id: "3",
      createdAt: "2026-01-08T16:45:00Z",
      name: "Priya Sharma",
      age: 26,
      city: "Chicago",
      gender: "Female",
      religion: "Hindu",
      maritalStatus: "Never Married",
      education: "Bachelor's Degree",
      profession: "Teacher",
      height: "5'4\"",
      image: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=500&q=80"
    },
    {
      id: "4",
      createdAt: "2026-01-08T09:20:00Z",
      name: "David Johnson",
      age: 35,
      city: "Houston",
      gender: "Male",
      religion: "Christian",
      maritalStatus: "Divorced",
      education: "Master's Degree",
      profession: "Doctor",
      height: "6'0\"",
      image: "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=500&q=80"
    },
    {
      id: "5",
      createdAt: "2026-01-07T12:00:00Z",
      name: "Fatima Ali",
      age: 29,
      city: "Phoenix",
      gender: "Female",
      religion: "Islam",
      maritalStatus: "Never Married",
      education: "Master's Degree",
      profession: "Architect",
      height: "5'5\"",
      image: "https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=500&q=80"
    },
    {
      id: "6",
      createdAt: "2026-01-06T18:30:00Z",
      name: "Raj Patel",
      age: 31,
      city: "Philadelphia",
      gender: "Male",
      religion: "Hindu",
      maritalStatus: "Never Married",
      education: "Bachelor's Degree",
      profession: "Accountant",
      height: "5'9\"",
      image: "https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=500&q=80"
    },
    {
      id: "7",
      createdAt: "2026-01-06T08:45:00Z",
      name: "Emily Wong",
      age: 27,
      city: "San Antonio",
      gender: "Female",
      religion: "Buddhist",
      maritalStatus: "Never Married",
      education: "Bachelor's Degree",
      profession: "Graphic Designer",
      height: "5'3\"",
      image: "https://images.unsplash.com/photo-1487412720507-e7ab37603c6f?w=500&q=80"
    },
    {
      id: "8",
      createdAt: "2026-01-05T15:10:00Z",
      name: "Ahmed Hassan",
      age: 34,
      city: "San Diego",
      gender: "Male",
      religion: "Islam",
      maritalStatus: "Never Married",
      education: "Doctorate",
      profession: "Engineer",
      height: "5'11\"",
      image: "https://images.unsplash.com/photo-1531427186611-ecfd6d936c79?w=500&q=80"
    },
    {
      id: "9",
      createdAt: "2026-01-05T11:25:00Z",
      name: "Jessica Martinez",
      age: 30,
      city: "Dallas",
      gender: "Female",
      religion: "Christian",
      maritalStatus: "Never Married",
      education: "Master's Degree",
      profession: "Nurse",
      height: "5'7\"",
      image: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&q=80"
    },
    {
      id: "10",
      createdAt: "2026-01-04T13:50:00Z",
      name: "Arjun Kumar",
      age: 33,
      city: "San Jose",
      gender: "Male",
      religion: "Hindu",
      maritalStatus: "Never Married",
      education: "Master's Degree",
      profession: "Data Scientist",
      height: "5'10\"",
      image: "https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=500&q=80"
    }
  ];

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const itemsPerPage = 5;

  useEffect(() => {
    // Initialize with dummy data first
    setProfiles(dummyProfiles);
    setTotalPages(Math.ceil(dummyProfiles.length / itemsPerPage));
    setLoading(false);
    
    // Then try to fetch from API
    fetchProfiles();
  }, [searchFilters, currentPage]);

  const fetchProfiles = async () => {
    setLoading(true);
    
    // Always show dummy data while loading
    setProfiles(dummyProfiles);
    setTotalPages(Math.ceil(dummyProfiles.length / itemsPerPage));
    
    try {
      const params = new URLSearchParams({
        gender: searchFilters.gender,
        location: searchFilters.location,
        searchText: searchFilters.searchText,
        minAge: searchFilters.minAge,
        maxAge: searchFilters.maxAge,
        religion: searchFilters.religion,
        maritalStatus: searchFilters.maritalStatus,
        education: searchFilters.education,
        profession: searchFilters.profession,
        minHeight: searchFilters.minHeight,
        maxHeight: searchFilters.maxHeight,
        sortBy: searchFilters.sortBy,
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });

      const response = await fetch(`/api/matrimony/profiles?${params}`);
      
      // Only process if we get a valid JSON response
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          const data = await response.json();
          if (data.profiles && data.profiles.length > 0) {
            setProfiles(data.profiles);
            setTotalPages(Math.ceil((data.total || data.profiles.length) / itemsPerPage));
          }
        }
      }
    } catch (error) {
      // Silently fail and keep dummy data
      console.log('Using dummy data - API endpoint not yet implemented');
    } finally {
      setLoading(false);
    }
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    setCurrentPage(1);
  };

  const handleFilterChange = (filterName, value) => {
    setSearchFilters(prev => ({
      ...prev,
      [filterName]: value
    }));
    setCurrentPage(1);
  };

  const handleSearchInputChange = (filterName, value) => {
    setSearchFilters(prev => ({
      ...prev,
      [filterName]: value
    }));
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm mb-6">
        <div className="container-full mx-auto px-4 py-6">
          <h1 className="text-3xl font-bold mb-2 text-brand-green-dark">Matrimony</h1>
          <p className="text-gray-600 mb-6">Find your perfect life partner</p>

          {/* Search Bar */}
          <form onSubmit={handleSearchSubmit} className="flex flex-col md:flex-row gap-3">
            <div className="flex-1 relative">
              <select
                value={searchFilters.gender}
                onChange={(e) => handleSearchInputChange('gender', e.target.value)}
                className="w-full text-gray-500 px-4 py-3 border border-gray-400 rounded-lg appearance-none bg-white pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Looking for</option>
                <option value="Male">Groom</option>
                <option value="Female">Bride</option>
              </select>
              <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
            </div>

            <div className="flex-1 relative">
              <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Location"
                value={searchFilters.location}
                onChange={(e) => handleSearchInputChange('location', e.target.value)}
                className="w-full text-gray-500 pl-10 pr-4 py-3 border border-gray-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search profiles..."
                value={searchFilters.searchText}
                onChange={(e) => handleSearchInputChange('searchText', e.target.value)}
                className="w-full text-gray-500 pl-10 pr-4 py-3 border border-gray-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <button
              type="submit"
              className="px-8 py-3 bg-brand-green cursor-pointer text-white rounded-lg hover:bg-brand-green-dark transition-colors font-medium flex items-center justify-center gap-2"
            >
              <Search className="w-5 h-5" />
              Search
            </button>
          </form>
        </div>
      </header>

      {/* Main Content */}
      <div className="container-full mx-auto px-4">
        <div className="flex flex-col lg:flex-row gap-6">
          {/* Left Sidebar - Filters */}
          <aside className="lg:w-64 flex-shrink-0">
            <div className="bg-white rounded-lg shadow-sm p-6 sticky top-4">
              <div className="flex items-center gap-2 mb-6">
                <SlidersHorizontal className="w-5 h-5 text-gray-700" />
                <h2 className="text-lg text-gray-700 font-bold">Filters</h2>
              </div>

              {/* Age Range */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Age Range</h3>
                <div className="flex gap-2">
                  <input
                    type="number"
                    placeholder="Min"
                    value={searchFilters.minAge}
                    onChange={(e) => handleFilterChange('minAge', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  <input
                    type="number"
                    placeholder="Max"
                    value={searchFilters.maxAge}
                    onChange={(e) => handleFilterChange('maxAge', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* Height Range */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Height</h3>
                <div className="flex gap-2">
                  <select
                    value={searchFilters.minHeight}
                    onChange={(e) => handleFilterChange('minHeight', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Min</option>
                    <option value="4'6">4&apos;6&quot;</option>
                    <option value="5'0">5&apos;0&quot;</option>
                    <option value="5'3">5&apos;3&quot;</option>
                    <option value="5'6">5&apos;6&quot;</option>
                    <option value="5'9">5&apos;9&quot;</option>
                    <option value="6'0">6&apos;0&quot;</option>
                  </select>
                  <select
                    value={searchFilters.maxHeight}
                    onChange={(e) => handleFilterChange('maxHeight', e.target.value)}
                    className="w-1/2 text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Max</option>
                    <option value="5'0">5&apos;0&quot;</option>
                    <option value="5'3">5&apos;3&quot;</option>
                    <option value="5'6">5&apos;6&quot;</option>
                    <option value="5'9">5&apos;9&quot;</option>
                    <option value="6'0">6&apos;0&quot;</option>
                    <option value="6'3">6&apos;3&quot;</option>
                  </select>
                </div>
              </div>

              {/* Religion */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Religion</h3>
                <select
                  value={searchFilters.religion}
                  onChange={(e) => handleFilterChange('religion', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Religions</option>
                  <option value="Islam">Islam</option>
                  <option value="Hindu">Hindu</option>
                  <option value="Christian">Christian</option>
                  <option value="Buddhist">Buddhist</option>
                  <option value="Sikh">Sikh</option>
                  <option value="Other">Other</option>
                </select>
              </div>

              {/* Marital Status */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Marital Status</h3>
                <select
                  value={searchFilters.maritalStatus}
                  onChange={(e) => handleFilterChange('maritalStatus', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Status</option>
                  <option value="Never Married">Never Married</option>
                  <option value="Divorced">Divorced</option>
                  <option value="Widowed">Widowed</option>
                  <option value="Separated">Separated</option>
                </select>
              </div>

              {/* Education */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Education</h3>
                <select
                  value={searchFilters.education}
                  onChange={(e) => handleFilterChange('education', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Education Levels</option>
                  <option value="High School">High School</option>
                  <option value="Bachelor's Degree">Bachelor&apos;s Degree</option>
                  <option value="Master's Degree">Master&apos;s Degree</option>
                  <option value="Doctorate">Doctorate</option>
                  <option value="Other">Other</option>
                </select>
              </div>

              {/* Profession */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Profession</h3>
                <input
                  type="text"
                  placeholder="e.g. Engineer, Doctor"
                  value={searchFilters.profession}
                  onChange={(e) => handleFilterChange('profession', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Sort By */}
              <div className="mb-6">
                <h3 className="font-semibold mb-3 text-sm text-gray-700">Sort By</h3>
                <select
                  value={searchFilters.sortBy}
                  onChange={(e) => handleFilterChange('sortBy', e.target.value)}
                  className="w-full text-gray-500 px-3 py-2 border border-gray-400 rounded-lg text-sm appearance-none bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="newest">Newest First</option>
                  <option value="oldest">Oldest First</option>
                  <option value="age-low">Age: Low to High</option>
                  <option value="age-high">Age: High to Low</option>
                  <option value="popular">Most Popular</option>
                </select>
              </div>

              {/* Reset Filters */}
              <button
                onClick={() => {
                  setSearchFilters({
                    gender: '',
                    location: '',
                    searchText: '',
                    minAge: '',
                    maxAge: '',
                    religion: '',
                    maritalStatus: '',
                    education: '',
                    profession: '',
                    minHeight: '',
                    maxHeight: '',
                    sortBy: 'newest'
                  });
                  setCurrentPage(1);
                }}
                className="w-full px-4 py-2 text-sm text-green-600 border border-green-600 rounded-lg hover:bg-green-50 transition-colors"
              >
                Reset All Filters
              </button>
            </div>
          </aside>

          {/* Right Content - Profiles Grid */}
          <main className="flex-1">
            {/* Results Info */}
            <div className="mb-4 flex items-center justify-between">
              <p className="text-gray-600">
                {loading ? 'Loading...' : `${profiles.length} profiles found`}
              </p>
            </div>

            {/* Profiles Grid */}
            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="bg-white rounded-lg shadow animate-pulse">
                    <div className="h-64 bg-gray-200 rounded-t-lg"></div>
                    <div className="p-4">
                      <div className="h-4 bg-gray-200 rounded mb-2"></div>
                      <div className="h-6 bg-gray-200 rounded w-1/2 mb-2"></div>
                      <div className="h-3 bg-gray-200 rounded w-1/3"></div>
                    </div>
                  </div>
                ))}
              </div>
            ) : profiles.length === 0 ? (
              <div className="bg-white rounded-lg shadow-sm p-12 text-center">
                <p className="text-gray-500 text-lg">No profiles found matching your criteria</p>
                <p className="text-gray-400 text-sm mt-2">Try adjusting your filters or search terms</p>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {profiles.map((profile) => (
                    <ProfileCard key={profile.id} profile={profile} />
                  ))}
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                  <div className="mt-8 flex justify-center items-center gap-2 mb-8">
                    <button
                      onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                      disabled={currentPage === 1}
                      className="px-4 py-2 border text-green-600 border border-green-600 hover:bg-green-50 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Previous
                    </button>

                    <div className="flex gap-2">
                      {[...Array(totalPages)].map((_, i) => {
                        const page = i + 1;
                        if (
                          page === 1 ||
                          page === totalPages ||
                          (page >= currentPage - 1 && page <= currentPage + 1)
                        ) {
                          return (
                            <button
                              key={page}
                              onClick={() => setCurrentPage(page)}
                              className={`px-4 py-2 rounded-lg ${
                                currentPage === page
                                  ? 'bg-green-600 text-white border border-green-600'
                                  : 'border text-green-600 border border-green-600 hover:bg-green-50'
                              }`}
                            >
                              {page}
                            </button>
                          );
                        } else if (page === currentPage - 2 || page === currentPage + 2) {
                          return <span key={page} className="px-2 py-2">...</span>;
                        }
                        return null;
                      })}
                    </div>

                    <button
                      onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                      disabled={currentPage === totalPages}
                      className="px-4 py-2 border text-green-600 border border-green-600 hover:bg-green-50 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                    </button>
                  </div>
                )}
              </>
            )}
          </main>
        </div>
      </div>
    </div>
  );
}

function ProfileCard({ profile }) {
  return (
    <Link href={`/matrimonial/${profile.id}`}>
      <div className="bg-white rounded-lg shadow hover:shadow-lg transition-shadow cursor-pointer overflow-hidden">
        <div className="h-64 bg-gray-200 relative">
          {profile.image ? (
            <img
              src={profile.image}
              alt={profile.name}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center bg-gray-300">
              <User className="w-20 h-20 text-gray-400" />
            </div>
          )}
          {profile.maritalStatus && (
            <span className="absolute top-2 right-2 px-2 py-1 text-gray-700 bg-green-100 text-xs font-medium rounded-full shadow">
              {profile.maritalStatus}
            </span>
          )}
        </div>
        <div className="p-4">
          <h3 className="font-bold text-lg mb-1 text-gray-800">{profile.name}</h3>
          <p className="text-sm text-gray-600 mb-2">
            {profile.age} years • {profile.height}
          </p>
          <div className="flex items-center text-sm text-gray-600 mb-1">
            <MapPin className="w-4 h-4 mr-1" />
            <span>{profile.city || 'Location not specified'}</span>
          </div>
          <p className="text-sm text-gray-600 mb-1">
            <span className="font-medium">Religion:</span> {profile.religion}
          </p>
          <p className="text-sm text-gray-600 mb-1">
            <span className="font-medium">Education:</span> {profile.education}
          </p>
          <p className="text-sm text-gray-600">
            <span className="font-medium">Profession:</span> {profile.profession}
          </p>
          {profile.createdAt && (
            <p className="text-xs text-gray-400 mt-2">
              Posted: {new Date(profile.createdAt).toLocaleDateString()}
            </p>
          )}
        </div>
      </div>
    </Link>
  );
}