import { MapPin, Phone, Mail, Calendar, User as UserIcon, GraduationCap, Briefcase } from "lucide-react";
import { useState } from "react";
import { EditBasicDetailsModal } from "./EditBasicDetailsModal";

export function BasicDetailsCard({ user }: { user: any }) {
  const profile = user?.seekerProfile;
  const address = user?.address; // Need to verify if address is inside profile or root in full API
  
  // Try to find the highest education
  const highestEdu = profile?.qualification || "Not specified";
  
  // Calculate total experience
  const totalExp = profile?.experience_duration || profile?.experience || "Not specified";

  // Calculate dynamic completion percentage
  const calculateCompletion = () => {
    // Define all the criteria that make up a 100% complete profile
    const criteria = [
      // 1. Basic Info
      !!(user?.full_name || user?.fullName || user?.first_name),
      !!user?.email,
      !!user?.phone,
      
      // 2. Profile Details
      !!(profile?.professional_title || profile?.current_job_title || profile?.headline),
      !!profile?.date_of_birth,
      !!profile?.gender,
      
      // 3. Address
      !!(address?.city || address?.state || address?.country),
      
      // 4. Arrays (Experience, Education, Skills, Languages)
      (user?.seekerExperiences?.length > 0 || user?.experiences?.length > 0),
      (user?.seekerEducations?.length > 0 || user?.educations?.length > 0),
      (user?.seekerSkills?.length > 0 || user?.skills?.length > 0),
      (user?.seekerLanguages?.length > 0 || user?.languages?.length > 0),
      
      // 5. Future fields (Certifications, Projects, Social Links)
      // These will naturally return false right now (0% contribution) and will
      // automatically start contributing to the score once the data is added to the user object!
      (user?.certifications?.length > 0),
      (user?.projects?.length > 0),
      (user?.socialLinks?.length > 0 || user?.seekerSocialLinks?.length > 0),
    ];

    // Count how many criteria are true
    const completedCount = criteria.filter(Boolean).length;
    
    // Calculate percentage and round to nearest whole number
    return Math.round((completedCount / criteria.length) * 100);
  };

  const completionPercent = calculateCompletion();

  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 relative">
      <button onClick={() => setIsEditModalOpen(true)} className="absolute top-4 right-4 text-sm font-medium text-[#ff6b00] hover:underline">
        Edit
      </button>

      {/* Top Section: Avatar & Name */}
      <div className="flex flex-col sm:flex-row items-center sm:items-start gap-5 mb-6">
        <div className="relative">
          {/* SVG Progress Ring */}
          <svg className="w-20 h-20 transform rotate-90">
            <circle
              className="text-gray-100"
              strokeWidth="5"
              stroke="currentColor"
              fill="transparent"
              r="36"
              cx="40"
              cy="40"
            />
            <circle
              className="text-[#ff6b00]"
              strokeWidth="5"
              strokeDasharray={36 * 2 * Math.PI}
              strokeDashoffset={36 * 2 * Math.PI * (1 - completionPercent / 100)}
              strokeLinecap="round"
              stroke="currentColor"
              fill="transparent"
              r="36"
              cx="40"
              cy="40"
            />
          </svg>
          {/* Avatar Image */}
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-16 h-16 rounded-full overflow-hidden bg-gray-100 border-2 border-white flex items-center justify-center">
              {profile?.profile_picture ? (
                <img src={profile.profile_picture} alt="Profile" className="w-full h-full object-cover" />
              ) : (
                <UserIcon className="w-6 h-6 text-gray-400" />
              )}
            </div>
          </div>
          <div className="absolute -bottom-2 left-1/2 -translate-x-1/2 bg-[#fff2ed] text-[#ff6b00] text-[10px] font-bold px-2 py-0.5 rounded-full border border-[#ff6b00]/20">
            {completionPercent}%
          </div>
        </div>

        <div className="flex flex-col items-center sm:items-start text-center sm:text-left mt-2">
          <h2 className="text-xl font-bold text-gray-900">
            {user?.full_name || user?.fullName || `${user?.first_name || ''} ${user?.last_name || ''}`.trim() || user?.username || 'Seeker'}
          </h2>
          <div className="flex items-center gap-2 text-gray-600 mt-1">
            <Briefcase className="w-4 h-4 text-[#ff6b00]" />
            <span className="text-sm font-medium">{profile?.professional_title || profile?.current_job_title || profile?.headline || 'Update your profile'}</span>
          </div>
          <div className="flex items-center gap-2 text-gray-500 mt-1">
            <MapPin className="w-4 h-4 text-[#ff6b00]" />
            <span className="text-sm">{address?.city || 'City'}, {address?.state || 'State'}</span>
          </div>
        </div>
      </div>

      <h3 className="font-semibold text-gray-900 text-lg mb-4">Basic Details</h3>
      
      {/* Grid of details */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {/* Phone */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5">
          <Phone className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div>
            <div className="font-medium text-gray-900 text-sm">{user?.phone || 'Not provided'}</div>
            <div className="text-xs text-gray-500 mt-0.5">Phone</div>
          </div>
        </div>

        {/* Email */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5 overflow-hidden">
          <Mail className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div className="min-w-0">
            <div className="font-medium text-gray-900 text-sm truncate" title={user?.email}>{user?.email || 'Not provided'}</div>
            <div className="text-xs text-gray-500 mt-0.5">Email</div>
          </div>
        </div>

        {/* Birthday */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5">
          <Calendar className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div>
            <div className="font-medium text-gray-900 text-sm">
              {profile?.date_of_birth ? new Date(profile.date_of_birth).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : 'Not provided'}
            </div>
            <div className="text-xs text-gray-500 mt-0.5">Birthday</div>
          </div>
        </div>

        {/* Gender */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5">
          <UserIcon className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div>
            <div className="font-medium text-gray-900 text-sm capitalize">{profile?.gender || 'Not provided'}</div>
            <div className="text-xs text-gray-500 mt-0.5">Gender</div>
          </div>
        </div>

        {/* Highest Qualification */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5">
          <GraduationCap className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div>
            <div className="font-medium text-gray-900 text-sm">{highestEdu}</div>
            <div className="text-xs text-gray-500 mt-0.5">Highest Qualification</div>
          </div>
        </div>

        {/* Experience */}
        <div className="bg-[#fff0e6] p-3 rounded-xl flex items-center gap-2.5">
          <Briefcase className="w-6 h-6 text-[#ff6b00] shrink-0" />
          <div>
            <div className="font-medium text-gray-900 text-sm">{profile?.experience_duration || profile?.experience || 'Not specified'}</div>
            <div className="text-xs text-gray-500 mt-0.5">Experience</div>
          </div>
        </div>
      </div>

      <EditBasicDetailsModal 
        isOpen={isEditModalOpen} 
        onClose={() => setIsEditModalOpen(false)} 
        user={user} 
      />
    </div>
  );
}
