import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';
import { 
  MapPin, 
  Phone, 
  Mail, 
  Calendar, 
  ChevronLeft, 
  ChevronRight,
  MessageCircle,
  User,
  Heart,
  Briefcase,
  GraduationCap,
  Home,
  Users,
  BookOpen,
  Globe,
  DollarSign,
  Clock,
  CheckCircle,
  XCircle,
  Send
} from 'lucide-react';

export default function MatrimonialDetailPage() {
  const router = useRouter();
  const { id } = router.query;
  
  const [profile, setProfile] = useState(null);
  const [loading, setLoading] = useState(true);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [showInterestModal, setShowInterestModal] = useState(false);

  // Dummy data
  const dummyProfiles = [
    {
      id: "1",
      createdAt: "2026-01-10T14:30:00Z",
      name: "Sarah Ahmed",
      age: 28,
      gender: "Female",
      city: "New York",
      country: "USA",
      religion: "Islam",
      maritalStatus: "Never Married",
      profileFor: "Self",
      images: [
        "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=800&q=80",
        "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=800&q=80",
        "https://images.unsplash.com/photo-1524504388940-b1c1722653e1?w=800&q=80"
      ],
      about: "I am a kind-hearted and ambitious person who values family, faith, and personal growth. I enjoy reading, traveling, and spending quality time with loved ones. Looking for someone who shares similar values and is ready to build a meaningful life together.",
      education: {
        degree: "Master's in Computer Science",
        institution: "Columbia University",
        year: "2020"
      },
      career: {
        profession: "Software Engineer",
        company: "Tech Corp",
        income: "$80,000 - $100,000 annually"
      },
      physicalAttributes: {
        height: "5'6\"",
        weight: "58 kg",
        bodyType: "Slim",
        complexion: "Fair"
      },
      familyDetails: {
        fatherOccupation: "Business Owner",
        motherOccupation: "Homemaker",
        siblings: "1 Brother, 1 Sister",
        familyType: "Nuclear",
        familyValues: "Moderate"
      },
      lifestyle: {
        diet: "Non-Vegetarian",
        smoking: "No",
        drinking: "No"
      },
      partnerPreferences: {
        ageRange: "28-35 years",
        heightRange: "5'8\" - 6'2\"",
        education: "Graduate or above",
        profession: "Any",
        location: "Open to relocate"
      },
      contact: {
        phone: "+1 (555) 123-4567",
        email: "sarah.ahmed@example.com",
        whatsapp: "+1 (555) 123-4567"
      }
    },
    {
      id: "2",
      createdAt: "2026-01-09T10:15:00Z",
      name: "Ahmed Khan",
      age: 32,
      gender: "Male",
      city: "Los Angeles",
      country: "USA",
      religion: "Islam",
      maritalStatus: "Never Married",
      profileFor: "Self",
      images: [
        "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=800&q=80",
        "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=800&q=80"
      ],
      about: "A dedicated professional who believes in maintaining a balanced life. I value honesty, respect, and mutual understanding in relationships. In my free time, I enjoy sports, reading, and exploring new places.",
      education: {
        degree: "MBA in Finance",
        institution: "UCLA",
        year: "2018"
      },
      career: {
        profession: "Financial Analyst",
        company: "Investment Firm",
        income: "$90,000 - $120,000 annually"
      },
      physicalAttributes: {
        height: "5'10\"",
        weight: "75 kg",
        bodyType: "Athletic",
        complexion: "Wheatish"
      },
      familyDetails: {
        fatherOccupation: "Retired Government Officer",
        motherOccupation: "Teacher",
        siblings: "2 Sisters",
        familyType: "Joint",
        familyValues: "Traditional"
      },
      lifestyle: {
        diet: "Non-Vegetarian",
        smoking: "No",
        drinking: "Occasionally"
      },
      partnerPreferences: {
        ageRange: "25-30 years",
        heightRange: "5'3\" - 5'8\"",
        education: "Graduate or above",
        profession: "Working or Homemaker",
        location: "USA or willing to relocate"
      },
      contact: {
        phone: "+1 (555) 234-5678",
        email: "ahmed.khan@example.com",
        whatsapp: "+1 (555) 234-5678"
      }
    }
  ];

  useEffect(() => {
    if (id) {
      fetchProfileDetails();
    }
  }, [id]);

  // Auto-slide effect
  useEffect(() => {
    if (profile?.images && profile.images.length > 1) {
      const interval = setInterval(() => {
        setCurrentImageIndex((prev) => (prev + 1) % profile.images.length);
      }, 4000);

      return () => clearInterval(interval);
    }
  }, [profile?.images]);

  const fetchProfileDetails = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/matrimonial/profiles/${id}`);
      
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          const data = await response.json();
          setProfile(data.profile);
        } else {
          throw new Error('Invalid response');
        }
      } else {
        throw new Error('Profile not found');
      }
    } catch (error) {
      console.log('Using dummy data - API endpoint not yet implemented');
      const dummyProfile = dummyProfiles.find(p => p.id === id);
      setProfile(dummyProfile || null);
    } finally {
      setLoading(false);
    }
  };

  const handleExpressInterest = async (formData) => {
    try {
      const response = await fetch('/api/matrimonial/interest', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          profileId: id,
          ...formData
        })
      });

      if (response.ok) {
        alert('Interest sent successfully! The profile owner will be notified.');
        setShowInterestModal(false);
      } else {
        throw new Error('Failed to send interest');
      }
    } catch (error) {
      console.log('Simulating interest submission...');
      alert('Interest sent successfully! The profile owner will be notified.');
      setShowInterestModal(false);
    }
  };

  const nextImage = () => {
    if (profile?.images) {
      setCurrentImageIndex((prev) => (prev + 1) % profile.images.length);
    }
  };

  const prevImage = () => {
    if (profile?.images) {
      setCurrentImageIndex((prev) => (prev - 1 + profile.images.length) % profile.images.length);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-green"></div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-800 mb-4">Profile not found</h2>
          <Link href="/matrimonial">
            <button className="px-6 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark">
              Back to Matrimonial
            </button>
          </Link>
        </div>
      </div>
    );
  }

  const whatsappUrl = `https://wa.me/${profile.contact?.whatsapp?.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(`Hi, I viewed your matrimonial profile: ${profile.name}`)}`;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm mb-6">
        <div className="container-full mx-auto px-4 py-4">
          <Link href="/matrimonial">
            <button className="flex items-center text-brand-green hover:text-brand-green-dark">
              <ChevronLeft className="w-5 h-5 mr-1" />
              Back to Matrimonial
            </button>
          </Link>
        </div>
      </div>

      <div className="container-full mx-auto px-4 pb-8">
        {/* Profile Header */}
        <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-6">
            <div className="flex-1">
              <div className="flex items-start gap-4 mb-4">
                <div className="w-24 h-24 bg-gradient-to-br from-brand-green to-brand-green-dark rounded-full flex items-center justify-center text-white text-3xl font-bold">
                  {profile.name.charAt(0)}
                </div>
                <div>
                  <h1 className="text-3xl font-bold text-gray-800 mb-2">{profile.name}</h1>
                  <div className="flex flex-wrap items-center gap-4 text-sm text-gray-600">
                    <div className="flex items-center gap-1">
                      <Calendar className="w-4 h-4" />
                      <span>{profile.age} years</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <MapPin className="w-4 h-4" />
                      <span>{profile.city}, {profile.country}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Heart className="w-4 h-4" />
                      <span>{profile.maritalStatus}</span>
                    </div>
                  </div>
                  <div className="mt-2">
                    <span className="inline-block px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
                      Profile for: {profile.profileFor}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="text-right">
              <p className="text-sm text-gray-500 mb-1">Profile ID</p>
              <p className="text-xl font-bold text-brand-green">#{profile.id}</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left Column - Photos and Details */}
          <div className="lg:col-span-2 space-y-6">
            {/* Photo Gallery */}
            <div className="bg-white rounded-lg shadow-sm overflow-hidden">
              <div className="relative h-[500px] bg-gray-200">
                {profile.images && profile.images.length > 0 ? (
                  <>
                    <img
                      src={profile.images[currentImageIndex]}
                      alt={profile.name}
                      className="w-full h-full object-cover"
                    />
                    {profile.images.length > 1 && (
                      <>
                        <button
                          onClick={prevImage}
                          className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white p-2 rounded-full shadow-lg transition-all"
                        >
                          <ChevronLeft className="w-6 h-6 text-gray-800" />
                        </button>
                        <button
                          onClick={nextImage}
                          className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white p-2 rounded-full shadow-lg transition-all"
                        >
                          <ChevronRight className="w-6 h-6 text-gray-800" />
                        </button>
                        
                        <div className="absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1 rounded-full text-sm">
                          {currentImageIndex + 1} / {profile.images.length}
                        </div>

                        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
                          {profile.images.map((_, idx) => (
                            <button
                              key={idx}
                              onClick={() => setCurrentImageIndex(idx)}
                              className={`w-2 h-2 rounded-full transition-all ${
                                currentImageIndex === idx 
                                  ? 'bg-brand-green w-8' 
                                  : 'bg-white/60 hover:bg-white'
                              }`}
                            />
                          ))}
                        </div>
                      </>
                    )}
                  </>
                ) : (
                  <div className="flex items-center justify-center h-full">
                    <User className="w-24 h-24 text-gray-400" />
                  </div>
                )}
              </div>

              {profile.images && profile.images.length > 1 && (
                <div className="flex gap-2 p-4 overflow-x-auto">
                  {profile.images.map((img, idx) => (
                    <button
                      key={idx}
                      onClick={() => setCurrentImageIndex(idx)}
                      className={`flex-shrink-0 w-20 h-20 rounded-lg overflow-hidden border-2 transition-all ${
                        currentImageIndex === idx ? 'border-brand-green' : 'border-gray-200 hover:border-gray-400'
                      }`}
                    >
                      <img src={img} alt={`Photo ${idx + 1}`} className="w-full h-full object-cover" />
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* About */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                <BookOpen className="w-5 h-5 text-brand-green" />
                About Me
              </h2>
              <p className="text-gray-700 leading-relaxed">
                {profile.about}
              </p>
            </div>

            {/* Education & Career */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                  <GraduationCap className="w-5 h-5 text-brand-green" />
                  Education
                </h2>
                <div className="space-y-3">
                  <div>
                    <p className="text-sm text-gray-500">Degree</p>
                    <p className="text-gray-800 font-medium">{profile.education.degree}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Institution</p>
                    <p className="text-gray-800">{profile.education.institution}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Year</p>
                    <p className="text-gray-800">{profile.education.year}</p>
                  </div>
                </div>
              </div>

              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                  <Briefcase className="w-5 h-5 text-brand-green" />
                  Career
                </h2>
                <div className="space-y-3">
                  <div>
                    <p className="text-sm text-gray-500">Profession</p>
                    <p className="text-gray-800 font-medium">{profile.career.profession}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Company</p>
                    <p className="text-gray-800">{profile.career.company}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Annual Income</p>
                    <p className="text-gray-800">{profile.career.income}</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Physical Attributes & Lifestyle */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold text-gray-800 mb-4">Physical Attributes</h2>
                <div className="grid grid-cols-2 gap-4">
                  {Object.entries(profile.physicalAttributes).map(([key, value]) => (
                    <div key={key} className="border-b border-gray-200 pb-2">
                      <p className="text-sm text-gray-500 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</p>
                      <p className="text-gray-800 font-medium">{value}</p>
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold text-gray-800 mb-4">Lifestyle</h2>
                <div className="grid grid-cols-2 gap-4">
                  {Object.entries(profile.lifestyle).map(([key, value]) => (
                    <div key={key} className="border-b border-gray-200 pb-2">
                      <p className="text-sm text-gray-500 capitalize">{key}</p>
                      <p className="text-gray-800 font-medium">{value}</p>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Family Details */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                <Users className="w-5 h-5 text-brand-green" />
                Family Details
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {Object.entries(profile.familyDetails).map(([key, value]) => (
                  <div key={key} className="border-b border-gray-200 pb-2">
                    <p className="text-sm text-gray-500 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</p>
                    <p className="text-gray-800 font-medium">{value}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Partner Preferences */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                <Heart className="w-5 h-5 text-brand-green" />
                Partner Preferences
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {Object.entries(profile.partnerPreferences).map(([key, value]) => (
                  <div key={key} className="border-b border-gray-200 pb-2">
                    <p className="text-sm text-gray-500 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</p>
                    <p className="text-gray-800 font-medium">{value}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Right Column - Quick Info and Actions */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-sm p-6 sticky top-4 space-y-6">
              {/* Quick Info */}
              <div>
                <h3 className="font-semibold text-gray-800 mb-4">Quick Info</h3>
                <div className="space-y-3">
                  <div className="flex items-center justify-between py-2 border-b border-gray-200">
                    <span className="text-sm text-gray-600">Age</span>
                    <span className="font-medium text-gray-800">{profile.age} years</span>
                  </div>
                  <div className="flex items-center justify-between py-2 border-b border-gray-200">
                    <span className="text-sm text-gray-600">Gender</span>
                    <span className="font-medium text-gray-800">{profile.gender}</span>
                  </div>
                  <div className="flex items-center justify-between py-2 border-b border-gray-200">
                    <span className="text-sm text-gray-600">Height</span>
                    <span className="font-medium text-gray-800">{profile.physicalAttributes.height}</span>
                  </div>
                  <div className="flex items-center justify-between py-2 border-b border-gray-200">
                    <span className="text-sm text-gray-600">Religion</span>
                    <span className="font-medium text-gray-800">{profile.religion}</span>
                  </div>
                  <div className="flex items-center justify-between py-2 border-b border-gray-200">
                    <span className="text-sm text-gray-600">Marital Status</span>
                    <span className="font-medium text-gray-800">{profile.maritalStatus}</span>
                  </div>
                  <div className="flex items-center gap-2 py-2">
                    <MapPin className="w-4 h-4 text-gray-500" />
                    <span className="text-sm text-gray-700">{profile.city}, {profile.country}</span>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="space-y-3 pt-4 border-t border-gray-200">
                <button
                  onClick={() => setShowInterestModal(true)}
                  className="w-full px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark flex items-center justify-center gap-2 font-medium"
                >
                  <Heart className="w-5 h-5" />
                  Express Interest
                </button>

                <a 
                  href={whatsappUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-full px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center justify-center gap-2 font-medium"
                >
                  <MessageCircle className="w-5 h-5" />
                  WhatsApp
                </a>

                <a 
                  href={`tel:${profile.contact?.phone}`}
                  className="w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center gap-2 font-medium"
                >
                  <Phone className="w-5 h-5" />
                  Call Now
                </a>

                <a 
                  href={`mailto:${profile.contact?.email}`}
                  className="w-full px-6 py-3 border-2 border-brand-green text-brand-green rounded-lg hover:bg-brand-green hover:text-white flex items-center justify-center gap-2 font-medium transition-all"
                >
                  <Mail className="w-5 h-5" />
                  Send Email
                </a>
              </div>

              {/* Posted Date */}
              <div className="pt-4 border-t border-gray-200">
                <div className="flex items-center gap-2 text-gray-600 text-sm">
                  <Clock className="w-4 h-4" />
                  <span>Profile created: {new Date(profile.createdAt).toLocaleDateString()}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Interest Modal */}
      {showInterestModal && (
        <InterestModal
          profile={profile}
          onClose={() => setShowInterestModal(false)}
          onSubmit={handleExpressInterest}
        />
      )}
    </div>
  );
}

function InterestModal({ profile, onClose, onSubmit }) {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    message: ''
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-2xl font-bold text-gray-800">Express Interest</h2>
            <button
              onClick={onClose}
              className="text-gray-500 hover:text-gray-700"
            >
              <XCircle className="w-6 h-6" />
            </button>
          </div>

          {/* Profile Summary */}
          <div className="bg-gradient-to-r from-brand-green/10 to-brand-green-dark/10 rounded-lg p-4 mb-6">
            <h3 className="font-semibold text-gray-700 mb-1">Sending interest to:</h3>
            <p className="text-lg font-bold text-brand-green">{profile.name}</p>
            <p className="text-sm text-gray-600">{profile.age} years, {profile.city}</p>
          </div>

          {/* Interest Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Your Name *
              </label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full text-gray-700 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="John Doe"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Your Email *
              </label>
              <input
                type="email"
                required
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="w-full text-gray-700 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="john@example.com"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Your Phone Number *
              </label>
              <input
                type="tel"
                required
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                className="w-full text-gray-700 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="+1 (555) 123-4567"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Message *
              </label>
              <textarea
                required
                value={formData.message}
                onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                className="w-full text-gray-700 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                rows="4"
                placeholder="Introduce yourself and express your interest..."
              />
            </div>

            <div className="flex gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="flex-1 px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark flex items-center justify-center gap-2"
              >
                <Send className="w-5 h-5" />
                Send Interest
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}