import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import School from "@material-ui/icons/School";
import PermIdentity from '@material-ui/icons/PermIdentity';
import Description from '@material-ui/icons/Description';
import Work from "@material-ui/icons/Work";
import Code from "@material-ui/icons/Code";
import GitHub from "@material-ui/icons/GitHub";
import GridContainer from "/components/Grid/GridContainer.js";
import GridItem from "/components/Grid/GridItem.js";
import CustomTabs from "/components/CustomTabs/CustomTabs.js";
import styles from "/styles/jss/nextjs-material-kit/pages/componentsSections/tabsStyle.js";
import Education from '../../components/Profile/Education';
import Experience from '../../components/Profile/Experience';
import Leetcode from '../../components/Profile/Leetcode';
import Github from '../../components/Profile/Github';

import Extras from '../../components/Profile/Extras';
import { getServerAuthSession } from "../../lib/auth";
import { fetchUserProfile, updateUserProfile, getVerifiedUser } from '../../utils/api';
import CustomLinearProgress from "/components/CustomLinearProgress/CustomLinearProgress.js";
import BasicInfo from '../../components/Profile/BasicInfo';

const useStyles = makeStyles(styles);

const defaultProfileData = {
  basicInfo: {
    name: '',
    email: '',
    universityEmail: '',
    phone: '',
    city: '',
    minimumSalary: 60000,
    international: '',
    countryOfOrigin: '', 
    relocationWillingness: '', // Added Relocation 
    gpa: '', // Added GPA
    linkedinUrl: '', // Added LinkedIn URL
    twitterUrl: '',  // Added Twitter URL
    jobType: '',
  },
  educations: [{ university: '', universityLocation: '', degree: '', fieldOfStudy: '', yearFrom: '', yearTo: '' }],
  experiences: [{
    type: '',
    title: '',
    company: '',
    startDate: '',
    endDate: '',
    techStack: '',
    linkedinUrl: '',
    // tier: 0,
    points: [{ what: '', impact: '' }]
  }],
  leetcode: { username: '', userData: null },
  github: { 
    stars: '', 
    username: '',
    projects: [{
      type: '',
      name: '',
      role: '',
      githubUrl: '',
      startDate: '',
      endDate: '',
      techStack: '',
      points: [{ what: '', impact: '' }, { what: '', impact: '' }]
    }]
  },
};

const tier1Companies = [
  'Google', 'Amazon', 'Facebook (Meta)', 'Apple', 'Microsoft', 'Netflix',
  'OpenAI', 'DeepMind', 'Anthropic', 'Nvidia', 'Tesla', 'SpaceX',
  'Stripe', 'Shopify', 'Salesforce', 'Airbnb', 'Uber', 'Lyft',
  'Palantir', 'Databricks', 'Snowflake', 'Zoom', 'Slack', 'Dropbox', 
  'Doordash', 'Instacart', 'Robinhood', 'Coinbase', 'Brex', 'Asana', 
  'HubSpot', 'Atlassian', 'Adobe', 'Splunk', 'Twilio', 
  'Citadel', 'Jane Street', 'Hudson River Trading', 
  'Renaissance Technologies', 'D.E. Shaw', 'Two Sigma', 'Jump Trading' 
];

// Tier 2 Companies (Well-known Tech & Non-Tech):
const tier2Companies = [
  'Square', 'Pinterest', 'Spotify', 'Reddit', 'Cloudflare', 'Okta', 'MongoDB', 
  'Twilio', 'Shopify', 'DocuSign', 'ServiceNow', 'Workday', 
  'Qualcomm', 'Intel', 'AMD', 'Broadcom', 'Marvell', 
  'Goldman Sachs', 'JPMorgan Chase', 'Morgan Stanley', 
  'McKinsey & Company', 'Boston Consulting Group', 'Bain & Company', 
  'Accenture', 'Deloitte', 'PwC', 'EY', 
  'Bell Canada', 'Rogers Communications', 'Telus', 
  'Canadian National Railway', 'Enbridge', 'TD Bank', 
  'Royal Bank of Canada', 'Bank of Montreal', 'Scotiabank'
];

// Tier 3 Companies (Still Well-Known, Maybe Not as Highly Paid)
const tier3Companies = [
  'CIBC', 'Desjardins Group', 'Manulife', 'Sun Life Financial',
  'Great-West Lifeco', 'Power Corporation of Canada', 'Hydro-Québec', 
  'BCE Inc.', 'Loblaw Companies', 'George Weston Limited', 
  'Magna International', 'Bombardier', 'SNC-Lavalin', 'CGI Inc.',
  'Imperial Oil', 'Canadian Natural Resources', 'Cenovus Energy',
  'Suncor Energy', 'Teck Resources', 'Barrick Gold',
  'Agnico Eagle Mines', 'Kinross Gold', 'First Quantum Minerals'
];

const CACHE_KEY = 'user_profile_cache';

const getCachedProfile = () => {
  if (typeof window !== 'undefined') {
    const cachedData = localStorage.getItem(CACHE_KEY);
    return cachedData ? JSON.parse(cachedData) : null;
  }
  return null;
};

const setCachedProfile = (data) => {
  if (typeof window !== 'undefined') {
    localStorage.setItem(CACHE_KEY, JSON.stringify(data));
  }
};

export default function Profile({ serverSession }) {
  const router = useRouter();
  const classes = useStyles();

  const [profileData, setProfileData] = useState(defaultProfileData);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [completionPercentage, setCompletionPercentage] = useState(0);
  const [incompleteTabsMap, setIncompleteTabsMap] = useState({});


  useEffect(() => {
    if (!serverSession) {
      router.push('/login');
    } else {
      const cachedData = getCachedProfile();
      if (cachedData) {
        setProfileData(cachedData);
        setLoading(false);
      }
      fetchProfileData();
    }
  }, [serverSession, router]);

  useEffect(() => {
    const percentage = calculateCompletionPercentage(profileData);
    setCompletionPercentage(percentage);
    updateIncompleteTabsMap(profileData);
  }, [profileData]);

  const fetchProfileData = async () => {
    try {
      const data = await fetchUserProfile(serverSession.user.id);
      setProfileData(data);
      setCachedProfile(data);
    } catch (err) {
      console.error('Error fetching profile:', err);
      setError('Failed to load profile data. Using cached or default profile.');
      if (!getCachedProfile()) {
        setProfileData(defaultProfileData);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      const verifieduser = await getVerifiedUser(serverSession.user.id);
      const emailVerified = verifieduser.emailVerified;
      const dataToSave = {
        ...profileData,
        completionPercentage: completionPercentage,
        emailVerified: emailVerified
      };
      const updatedProfile = await updateUserProfile(dataToSave);
      
      setCachedProfile(updatedProfile);
      // Handle successful save (e.g., show a success message)
    } catch (error) {
      console.error('Error saving profile:', error);
      // Handle error (e.g., show an error message to the user)
    }
  };

  const handleEducationChange = (index, event) => {
    setProfileData(prevState => ({
      ...prevState,
      educations: prevState.educations.map((education, i) =>
        i === index ? { ...education, [event.target.name]: event.target.value } : education
      ),
    }));
  };

  const addEducation = (event) => {
    event.preventDefault();
    if (profileData.educations.length < 3) {
      setProfileData(prevState => ({
        ...prevState,
        educations: [
          ...prevState.educations,
          { university: '', universityLocation: '', degree: '', fieldOfStudy: '', yearFrom: '', yearTo: '' },
        ],
      }));
    }
  };



  const handleExperienceChange = (index, field, value) => {
    setProfileData(prevState => ({
      ...prevState,
      experiences: prevState.experiences.map((experience, i) =>
        i === index
          ? { 
              ...experience, 
              [field]: value, 
              // Only update tier if the field being changed is 'company'
              ...(field === 'company' ? { tier: getCompanyTier(value) } : {})
            }
          : experience
      ),
    }));
  };

  const getCompanyTier = (company) => {
    // If company is undefined or null, return 0 (default tier)
    if (!company) {
      return 0;
    }
  
    const lowerCaseCompany = company.toLowerCase();
    if (tier1Companies.some(tier1Company => tier1Company.toLowerCase().includes(lowerCaseCompany))) {
      return 1;
    } else if (tier2Companies.some(tier2Company => tier2Company.toLowerCase().includes(lowerCaseCompany))) {
      return 2;
    } else if (tier3Companies.some(tier3Company => tier3Company.toLowerCase().includes(lowerCaseCompany))) {
      return 3;
    }
    return 0;
  };
  
  const handleTechStackChange = (index, event) => {
    const techStack = event.target.value
      .split(',')
      .map(tech => tech.trim().charAt(0).toUpperCase() + tech.trim().slice(1))
      .join(', ');
  
    handleExperienceChange(index, 'techStack', techStack);
  };
  
  const handlePointChange = (experienceIndex, pointIndex, field, value) => {
    setProfileData(prevState => ({
      ...prevState,
      experiences: prevState.experiences.map((experience, i) =>
        i === experienceIndex
          ? {
              ...experience,
              points: experience.points.map((point, j) =>
                j === pointIndex ? { ...point, [field]: value } : point
              ),
            }
          : experience
      ),
    }));
  };

  const addExperience = (event) => {
    event.preventDefault();
    if (profileData.experiences.length < 8) {
      setProfileData(prevState => ({
        ...prevState,
        experiences: [
          ...prevState.experiences,
          { type: '', title: '', company: '', startDate: '', endDate: '', techStack: '', points: [{ what: '', impact: '' }] },
        ],
      }));
    }
  };


  const handleUsernameChange = (event) => {
    setProfileData(prevState => ({
      ...prevState,
      leetcode: {
        ...prevState.leetcode,
        username: event.target.value,
      },
    }));
    setError(null); 
  };

  const fetchUserData = async (event) => {
    event.preventDefault();
    try {
      const response = await fetch(`/api/leetcode-user?username=${encodeURIComponent(profileData.leetcode.username)}`);
      if (!response.ok) {
        throw new Error('Failed to fetch user data');
      }
      const data = await response.json();
      setProfileData(prevState => ({
        ...prevState,
        leetcode: {
          ...prevState.leetcode,
          userData: data,
        },
      }));
    } catch (err) {
      setError('Failed to fetch user data. Please check the username and try again.');
    }
  };

  const applyRedHotShadow = (userData) => {
    if (!userData) return false;
    const totalSolved = userData.submitStats.acSubmissionNum.reduce((acc, stat) => acc + stat.count, 0);
    const contestRating = userData.userContestRanking ? userData.userContestRanking.rating : 0;
    const activeYears = userData.userCalendar.activeYears.length;
    const totalActiveDays = userData.userCalendar.totalActiveDays;

    return (
      totalSolved > 700 ||
      (contestRating > 1850 && (activeYears > 1 || totalActiveDays > 100)) ||
      (contestRating > 1850 && totalActiveDays > 150)
    );
  };

  const handleGithubChange = (event) => {
    setProfileData(prevState => ({
      ...prevState,
      github: {
        ...prevState.github,
        [event.target.name]: event.target.value,
      },
    }));
  };

  const handleProjectChange = (index, field, value) => {
    setProfileData(prevState => ({
      ...prevState,
      github: {
        ...prevState.github,
        projects: prevState.github.projects.map((project, i) =>
          i === index ? { ...project, [field]: value } : project
        ),
      },
    }));
  };
  
  const handleProjectTechStackChange = (index, event) => {
    const techStack = event.target.value
      .split(',')
      .map(tech => tech.trim().charAt(0).toUpperCase() + tech.trim().slice(1))
      .join(', ');
  
    handleProjectChange(index, 'techStack', techStack);
  };
  
  const addProject = (event) => {
    event.preventDefault();
    if (profileData.github.projects.length < 3) {
      setProfileData(prevState => ({
        ...prevState,
        github: {
          ...prevState.github,
          projects: [
            ...prevState.github.projects,
            {
              type: '',
              name: '',
              role: '',
              githubUrl: '',
              startDate: '',
              endDate: '',
              techStack: '',
              points: [{ what: '', impact: '' }, { what: '', impact: '' }]
            },
          ],
        },
      }));
    }
  };

  const handleBasicInfoChange = (event) => {
    setProfileData(prevState => ({
      ...prevState,
      basicInfo: {
        ...prevState.basicInfo,
        [event.target.name]: event.target.value,
      },
    }));
  };

  const handleSalarySliderChange = (values) => {
    setProfileData(prevState => ({
      ...prevState,
      basicInfo: {
        ...prevState.basicInfo,
        minimumSalary: Math.round(values[0]),
      },
    }));
  };

  const handleBasicDetailsChange = (event) => {
    setProfileData(prevState => ({
      ...prevState,
      basicInfo: {
        ...prevState.basicInfo,
        [event.target.name]: event.target.value,
      },
    }));
  };


  const renderTabContent = (TabComponent, props) => {
    if (loading) {
      return <div>Loading...</div>;
    }
    return <TabComponent {...props} />;
  };

  const calculateCompletionPercentage = (data) => {
    let totalFields = 0;
    let filledFields = 0;
    
    const countFields = (obj) => {
      for (const key in obj) {
        if (key === 'twitterUrl') continue; // Skip twitterUrl
        if (key === 'countryOfOrigin' && obj['international'] === 'no') continue; // Skip countryOfOrigin if not international
        if (key === 'tier') continue; 
  
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          countFields(obj[key]);
        } else {
          totalFields++;
          if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            filledFields++;
          }
        }
      }
    };
  
    countFields(data);
    return totalFields > 0 ? (filledFields / totalFields) * 100 : 0;
  };

  const updateIncompleteTabsMap = (data) => {
    const newIncompleteTabsMap = {
      basicInfo: !isTabComplete(data.basicInfo),
      education: !isTabComplete(data.educations),
      experience: !isTabComplete(data.experiences),
      leetcode: !isTabComplete(data.leetcode),
      github: !isTabComplete(data.github),
      extras: !isTabComplete(data.basicInfo, ['gpa', 'linkedinUrl', 'twitterUrl','jobType'])
    };
    setIncompleteTabsMap(newIncompleteTabsMap);
    // Log the experience tab status and the experiences data 
    console.log('Experience Tab Incomplete:', newIncompleteTabsMap.experience);
    
  };

  const isTabComplete = (data, fields = null) => {
    if (Array.isArray(data)) {
      return data.every(item => isTabComplete(item));
    }
    if (typeof data === 'object' && data !== null) {
      const keysToCheck = fields || Object.keys(data);
      return keysToCheck.every(key => {
        const value = data[key];
        console.log(`Checking field: ${key}, Value: ${value}`);  // Log each field being checked
        return value !== '' && value !== null && value !== undefined;
      });
    }
    return false;
  };

  const customTabStyle = (tabName) => {
    return incompleteTabsMap[tabName] 
      ? { 
          borderBottom: '2px solid red',
          color: 'red !important',  // Override the default white color
          fontWeight: 'bold'  // Make incomplete tabs stand out more
        } 
      : {};
  };

  return (
    <div className={classes.section}>
      <div className={classes.container}>
        <div id="nav-tabs">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
            <h3>Your Profile</h3>
            <div>
              <Button 
                variant="contained" 
                color="secondary"
                onClick={() => router.push('/v1/card')}
                style={{ marginRight: '10px' }}
              >
                Anonymous Card
              </Button>
              <Button 
                variant="contained" 
                color="primary"
                onClick={handleSave}
                style={{ backgroundColor: 'green', color: 'white' }}
              >
                Save
              </Button>
            </div>
          </div>
          {error && <p style={{color: 'red'}}>{error}</p>}

          <CustomLinearProgress
            variant="determinate"
            color="primary"
            value={completionPercentage}
          />
          <p>Profile Completion: {completionPercentage.toFixed(2)}%</p>
          
          <GridContainer>
            <GridItem xs={12} sm={12} md={12}>
              <CustomTabs
                headerColor="primary"
                tabs={[
                  {
                    tabName: "Basic Info",
                    tabIcon: PermIdentity,
                    tabContent: renderTabContent(BasicInfo, {
                      basicInfo: profileData.basicInfo,
                      handleBasicInfoChange,
                      handleSalarySliderChange,
                      handleBasicDetailsChange,
                    }),
                    tabStyle: customTabStyle('basicInfo'),
                  },
                  {
                    tabName: "Education",
                    tabIcon: School,
                    tabContent: renderTabContent(Education, {
                      educations: profileData.educations,
                      handleEducationChange,
                      addEducation,
                    }),
                    tabStyle: customTabStyle('education'),
                  },
                  {
                    tabName: "Experience",
                    tabIcon: Work,
                    tabContent: renderTabContent(Experience, {
                      experiences: profileData.experiences,
                      handleExperienceChange,
                      addExperience,
                      handleTechStackChange,
                      handlePointChange,
                    }),
                    tabStyle: customTabStyle('experience'),
                  },
                  {
                    tabName: "Leetcode",
                    tabIcon: Code,
                    tabContent: renderTabContent(Leetcode, {
                      username: profileData.leetcode.username,
                      userData: profileData.leetcode.userData,
                      handleUsernameChange,
                      fetchUserData,
                      applyRedHotShadow,
                    }),
                    tabStyle: customTabStyle('leetcode'),
                  },
                  {
                    tabName: "GitHub",
                    tabIcon: GitHub,
                    tabContent: renderTabContent(Github, {
                      github: profileData.github,
                      handleGithubChange,
                      handleProjectChange,
                      addProject,
                      projects: profileData.github.projects,
                      handleProjectTechStackChange,
                    }),
                    tabStyle: customTabStyle('github'),
                  },
                  {
                    tabName: "Screening",
                    tabIcon: Description,
                    tabContent: renderTabContent(Extras, {
                      basicInfo: profileData.basicInfo,
                      handleBasicDetailsChange,
                    }),
                    tabStyle: customTabStyle('extras'),
                  },
                ]}
              />
            </GridItem>
          </GridContainer>
        </div>
      </div>
    </div>
  );
}

export async function getServerSideProps(context) {
  const session = await getServerAuthSession(context);

  if (!session) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    };
  }
  // Ensure the role is defined or set to null
  const role = session.user.role || null;

  if (!role || session.user.role === 'recruiter') {
    return {
      redirect: {
        destination: '/v1/verify',
        permanent: false,
      },
    };
  }

  return {
    props: {
      serverSession: session,
    },
  };
}

Experience completition calculation is messed up. 
Even if experience is complete, it still says it's incomplete. However, when I save it and then refresh page(which fetches the same saved data from backend), now it says its complete. 

Checking field: points, Value: [object Object],[object Object],[object Object]
profile.js:472 Checking field: [object Object], Value: undefined

This is from the logs. Initially I thought tier is the culprit, but I commented it out.