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 (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);
  };

  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];
        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,
    },
  };
}

import React, { useState } from 'react';
import { makeStyles } from "@material-ui/core/styles";
import styles from "/styles/jss/nextjs-material-kit/pages/componentsSections/tabsStyle.js";
import CustomInput from "/components/CustomInput/CustomInput";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Grid from "@material-ui/core/Grid";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import TextField from "@material-ui/core/TextField";
import Chip from "@material-ui/core/Chip";

const useStyles = makeStyles(theme => ({
  ...styles,
  experienceCard: {
    marginBottom: '20px',
    borderRadius: '10px',
    transition: '0.3s',
    '&:hover': {
      boxShadow: '0 8px 16px 0 rgba(0,0,0,0.2)',
    },
  },
  addButton: {
    marginTop: '20px',
  },
  formControl: {
    width: '100%',
    marginTop: '16px',
  },
  typeSelect: {
    '& .MuiInputBase-root': {
      height: '32px',
      display: 'flex',
      alignItems: 'center',
    },
    '& .MuiInput-underline:before': {
      borderBottomWidth: '1px',
    },
    '& .MuiInput-underline:after': {
      borderBottomWidth: '2px',
    },
    '& .MuiInputLabel-formControl': {
      transform: 'translate(0, -1.5px) scale(0.75)',
      transformOrigin: 'top left',
    },
    '& .MuiInputBase-input': {
      paddingTop: '2px',
      paddingBottom: '5px',
    },
    '& .MuiSelect-select:focus': {
      backgroundColor: 'transparent',
    },
  },
  inputContainer: {
    display: 'flex',
    alignItems: 'center',
    marginTop: '8px',
  },
  inputItem: {
    margin: '0 8px',
    width: '100%',
  },
  redHotShadow: {
    boxShadow: '0 4px 12px 0 rgba(255,0,0,0.5)',
    animation: '$pulseRedHot 2s infinite',
  },
  '@keyframes pulseRedHot': {
    '0%': {
      boxShadow: '0 4px 12px 0 rgba(255,0,0,0.5)',
    },
    '50%': {
      boxShadow: '0 4px 20px 0 rgba(255,50,0,0.8), 0 0 30px 0 rgba(255,100,0,0.4)',
    },
    '100%': {
      boxShadow: '0 4px 12px 0 rgba(255,0,0,0.5)',
    },
  },
  goldShadow: {
    boxShadow: '0 4px 12px 0 rgba(255,215,0,0.5)',
    animation: '$pulseGold 2s infinite',
  },
  '@keyframes pulseGold': {
    '0%': {
      boxShadow: '0 4px 12px 0 rgba(255,215,0,0.5)',
    },
    '50%': {
      boxShadow: '0 4px 20px 0 rgba(255,215,0,0.8), 0 0 30px 0 rgba(255,215,0,0.4)',
    },
    '100%': {
      boxShadow: '0 4px 12px 0 rgba(255,215,0,0.5)',
    },
  },
  defaultShadow: {
    boxShadow: '0 4px 8px 0 rgba(0,0,0,0.2)',
  },
  pointContainer: {
    marginTop: '16px',
  },
  pointInput: {
    marginBottom: '8px',
    borderRadius: '4px',
    border: '2px solid #333',
    padding: '8px',
    position: 'relative',
  },
  bulletPoint: {
    position: 'absolute',
    left: '-15px',
    top: '50%',
    transform: 'translateY(-50%)',
    fontSize: '20px',
    fontWeight: 'bold',
  },
  chipContainer: {
    marginTop: '16px',
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
  },
  chip: {
    backgroundColor: '#e0e0e0',
  },
}));

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'
];

export default function Experience({ experiences, handleExperienceChange, addExperience, handleTechStackChange }) {
  const classes = useStyles();

  const formatDate = (value) => {
    if (value.length === 2 && !value.includes('/')) {
      return value + '/';
    }
    return value;
  };

  const handleDateChange = (index, event) => {
    const { name, value } = event.target;
    if (value.length <= 7 && /^[0-9/]*$/.test(value)) {
      const formattedValue = formatDate(value);
      // handleExperienceChange(index, { target: { name, value: formattedValue } });
      handleExperienceChange(index, name, formattedValue);
    }
  };

  const getShadowClass = (company) => {
    const lowerCaseCompany = company.toLowerCase(); 
    if (tier1Companies.some(tier1Company => tier1Company.toLowerCase().includes(lowerCaseCompany))) {
      return classes.redHotShadow;
    } else if (tier2Companies.some(tier2Company => tier2Company.toLowerCase().includes(lowerCaseCompany))) {
      return classes.goldShadow;
    } else if (tier3Companies.some(tier3Company => tier3Company.toLowerCase().includes(lowerCaseCompany))) {
      return classes.defaultShadow; // For now, Tier 3 uses the default shadow
    }
    return ''; // No shadow if no match 
  }; 

  const getCompanyTier = (company) => { 
    const lowerCaseCompany = company.toLowerCase();
    if (tier1Companies.some(tier1Company => tier1Company.toLowerCase().includes(lowerCaseCompany))) {
      return 1; // "Flame" color in CSS 
    } else if (tier2Companies.some(tier2Company => tier2Company.toLowerCase().includes(lowerCaseCompany))) {
      return 2; // "Gold" color
    } else if (tier3Companies.some(tier3Company => tier3Company.toLowerCase().includes(lowerCaseCompany))) {
      return 3; // "Silver" color
    } 
    return 0; // "White" - the default color  
  };

  const getPointCount = (experience) => {
    const { type, startDate, endDate } = experience;
    const duration = endDate ? getDuration(startDate, endDate) : 0;

    if (type === 'Internship') {
      return duration <= 3 ? 1 : 2;
    } else {
      return duration <= 18 ? 2 : 3;
    }
  };

  const getDuration = (startDate, endDate) => {
    const calculateMonths = (startDate, endDate) => {
      if (!startDate || !endDate) return 0;

      const parseDate = (dateString) => {
        const [month, year] = dateString.split('/');
        return new Date(parseInt(year), parseInt(month) - 1);
      };

      const start = parseDate(startDate);
      const end = parseDate(endDate);

      const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());

      return Math.floor(months);
    };

    const duration = calculateMonths(startDate, endDate);
    return duration + 1;
  };

  const handlePointChange = (index, pointIndex, field, value) => {
    const updatedExperiences = [...experiences];
    if (!updatedExperiences[index].points) {
      updatedExperiences[index].points = [];
    }
    if (!updatedExperiences[index].points[pointIndex]) {
      updatedExperiences[index].points[pointIndex] = {};
    }
    updatedExperiences[index].points[pointIndex][field] = value;
    handleExperienceChange(index, { points: updatedExperiences[index].points });
  };

  return (
    <div>
      {experiences.map((experience, index) => (
        <Card key={index} className={`${classes.experienceCard} ${getShadowClass(experience.company)}`}>
          <CardContent>
            <Grid container spacing={2}>
              <Grid item xs={6} className={classes.inputContainer}>
                <FormControl className={classes.inputItem}>
                  <InputLabel htmlFor={`type-${index}`} shrink>Type</InputLabel>
                  <Select
                    value={experience.type}
                    // onChange={(e) => handleExperienceChange(index, { target: { name: 'type', value: e.target.value } })}
                    onChange={(e) => handleExperienceChange(index, 'type', e.target.value)}
                    displayEmpty
                    className={classes.typeSelect}
                    inputProps={{ id: `type-${index}` }}
                  >
                    <MenuItem value="" disabled>Select Type</MenuItem>
                    <MenuItem value="Internship">Internship</MenuItem>
                    <MenuItem value="Full-Time">Full-Time</MenuItem>
                    <MenuItem value="Contract">Contract</MenuItem>
                    <MenuItem value="Freelance">Freelance</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={6} className={classes.inputContainer}>
                <CustomInput
                  labelText="Company Name"
                  id={`company-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: experience.company,
                    // onChange: (e) => handleExperienceChange(index, e),
                    onChange: (e) => handleExperienceChange(index, 'company', e.target.value),
                    name: "company"
                  }}
                />
              </Grid>
            </Grid>
            <Grid container spacing={2}>
              <Grid item xs={6} className={classes.inputContainer}> 
                <CustomInput
                  labelText="Job Title"
                  id={`title-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: experience.title, 
                    onChange: (e) => handleExperienceChange(index, 'title', e.target.value),
                    name: "title"
                  }}
                />
              </Grid>
              <Grid item xs={6} className={classes.inputContainer}> 
                <CustomInput
                  labelText="Company LinkedIn URL"
                  id={`linkedinUrl-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: experience.linkedinUrl || '',  
                    onChange: (e) => handleExperienceChange(index, 'linkedinUrl', e.target.value),
                    name: "linkedinUrl"
                  }}
                />
              </Grid>
            </Grid>
            <Grid container spacing={2} style={{ marginTop: '10px' }}>
              <Grid item xs={6}>
                <CustomInput
                  labelText="Start Date (MM/YYYY)"
                  id={`startDate-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: experience.startDate,
                    onChange: (e) => handleDateChange(index, e),
                    name: "startDate",
                    placeholder: "MM/YYYY"
                  }}
                />
              </Grid>
              <Grid item xs={6}>
                <CustomInput
                  labelText="End Date (MM/YYYY)"
                  id={`endDate-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: experience.endDate,
                    onChange: (e) => handleDateChange(index, e),
                    name: "endDate",
                    placeholder: "MM/YYYY"
                  }}
                />
              </Grid>
              
            </Grid>
            <TextField
              label="Tech Stack (Enter tech stack separated by commas) (The more you change the tech stack, the more points you lose)"
              variant="outlined"
              fullWidth
              value={experience.techStack}
              onChange={(e) => handleTechStackChange(index, e)}
              margin="normal"
              id={`techStack-${index}`}
            />
            <div className={classes.chipContainer}>
              {experience.techStack.split(',').map((tech, i) => (
                <Chip key={i} label={tech.trim()} className={classes.chip} />
              ))}
            </div>
            <div className={classes.pointContainer}>
              {Array.from({ length: getPointCount(experience) }, (_, i) => (
                <div key={i} className={classes.pointInput}>
                  <span className={classes.bulletPoint}>&#8226;</span>
                  <CustomInput
                    labelText="What you did(sentence must end with a full stop)"
                    id={`what-${index}-${i}`}
                    formControlProps={{ fullWidth: true }}
                    inputProps={{
                      name: `what-${i}`,
                      value: experience.points?.[i]?.what || '',
                      onChange: (event) => handlePointChange(index, i, 'what', event.target.value),
                    }}
                  />
                  <CustomInput
                    labelText="Impact it created(sentence must end with a full stop)"
                    id={`impact-${index}-${i}`}
                    formControlProps={{ fullWidth: true }}
                    inputProps={{
                      name: `impact-${i}`,
                      value: experience.points?.[i]?.impact || '',
                      onChange: (event) => handlePointChange(index, i, 'impact', event.target.value),
                    }}
                  />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      ))}
      {experiences.length < 8 && (
        <Button
          color="primary"
          onClick={addExperience}
          className={classes.addButton}
        >
          Add Experience
        </Button>
      )}
    </div>
  );
}

import React from 'react';
import { makeStyles } from "@material-ui/core/styles";
import styles from "/styles/jss/nextjs-material-kit/pages/componentsSections/tabsStyle.js";
import CustomInput from "/components/CustomInput/CustomInput";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Grid from "@material-ui/core/Grid";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import TextField from "@material-ui/core/TextField";
import Chip from "@material-ui/core/Chip";
import Input from "@material-ui/core/Input";  // Import the Input component


const useStyles = makeStyles(theme => ({
  ...styles,
  projectCard: {
    marginBottom: '20px',
    borderRadius: '10px',
    transition: '0.3s',
    '&:hover': {
      boxShadow: '0 8px 16px 0 rgba(0,0,0,0.2)',
    },
  },
  addButton: {
    marginTop: '20px',
  },
  formControl: {
    width: '100%',
    marginTop: '16px',
  },
  typeSelect: {
    '& .MuiInputBase-root': {
      height: '32px',
      display: 'flex',
      alignItems: 'center',
    },
    '& .MuiInput-underline:before': {
      borderBottomWidth: '1px',
    },
    '& .MuiInput-underline:after': {
      borderBottomWidth: '2px',
    },
    '& .MuiInputLabel-formControl': {
      transform: 'translate(0, -1.5px) scale(0.75)',
      transformOrigin: 'top left',
    },
    '& .MuiInputBase-input': {
      paddingTop: '2px',
      paddingBottom: '5px',
    },
    '& .MuiSelect-select:focus': {
      backgroundColor: 'transparent',
    },
  },
  inputContainer: {
    display: 'flex',
    alignItems: 'center',
    marginTop: '8px',
  },
  inputItem: {
    margin: '0 8px',
    width: '100%',
  },
  pointContainer: {
    marginTop: '16px',
  },
  pointInput: {
    marginBottom: '8px',
    borderRadius: '4px',
    border: '2px solid #333',
    padding: '8px',
    position: 'relative',
  },
  bulletPoint: {
    position: 'absolute',
    left: '-15px',
    top: '50%',
    transform: 'translateY(-50%)',
    fontSize: '20px',
    fontWeight: 'bold',
  },
  chipContainer: {
    marginTop: '16px',
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
  },
  chip: {
    backgroundColor: '#e0e0e0',
  },
  githubLinksContainer: { 
    display: 'flex',
    alignItems: 'center',
    gap: theme.spacing(2), 
    marginBottom: theme.spacing(2),
  },
}));

export default function Github({ 
  github, 
  handleGithubChange, 
  handleProjectChange, 
  addProject, 
  projects, 
  handleProjectTechStackChange 
}) {
  const classes = useStyles();

  const formatDate = (value) => {
    if (value.length === 2 && !value.includes('/')) {
      return value + '/';
    }
    return value;
  };

  const handleDateChange = (index, event) => {
    const { name, value } = event.target;
    if (value.length <= 7 && /^[0-9/]*$/.test(value)) {
      const formattedValue = formatDate(value);
      handleProjectChange(index, name, formattedValue); 
    }
  };

  const handlePointChange = (projectIndex, pointIndex, field, value) => {
    const updatedProjects = [...projects];
    updatedProjects[projectIndex].points[pointIndex][field] = value;
    handleProjectChange(projectIndex, 'points', updatedProjects[projectIndex].points);
  };

  return (
    <div>
      {/* GitHub Links (Horizontally Aligned) */}
      <div className={classes.githubLinksContainer}>
        <CustomInput
          labelText="GitHub Link"
          id="github-username"
          formControlProps={{ fullWidth: true }}
          inputProps={{
            name: "username",
            value: github.username,
            onChange: handleGithubChange,
          }}
        />
        <CustomInput
          labelText="GitHub Stars Earned"
          id="github-stars"
          formControlProps={{ fullWidth: true }}
          inputProps={{
            name: "stars",
            value: github.stars,
            onChange: handleGithubChange,
          }}
        />
      </div>

      {/* Projects Section */}
      {projects.map((project, index) => (
        <Card key={index} className={classes.projectCard}> 
          <CardContent>
            <Grid container spacing={2}>
              <Grid item xs={4} className={classes.inputContainer}>
                <FormControl className={classes.inputItem}>
                  <InputLabel htmlFor={`projectType-${index}`} shrink>Type</InputLabel>
                  <Select
                    value={project.type}
                    onChange={(e) => handleProjectChange(index, 'type', e.target.value)}
                    displayEmpty
                    className={classes.typeSelect}
                    inputProps={{ id: `projectType-${index}` }}
                  >
                    <MenuItem value="" disabled>Select Type</MenuItem>
                    <MenuItem value="Personal">Personal</MenuItem>
                    <MenuItem value="University">University</MenuItem>
                    <MenuItem value="Startup">Startup</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={8} className={classes.inputContainer}>
                <FormControl fullWidth>
                  <InputLabel htmlFor={`projectName-${index}`}>
                    Project Description (Max 50 characters allowed)
                  </InputLabel>
                  <Input
                    id={`projectName-${index}`}
                    value={project.name}
                    onChange={(e) => handleProjectChange(index, "name", e.target.value)}
                    name="name"
                    inputProps={{
                      maxLength: 50,  // Ensure maxLength is applied here
                    }}
                    fullWidth
                  />
                </FormControl>
              </Grid>
            </Grid>

            <Grid container spacing={2}>
              <Grid item xs={12} className={classes.inputContainer}>
                <CustomInput
                  labelText="Role Title"
                  id={`projectRole-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: project.role,
                    onChange: (e) => handleProjectChange(index, 'role', e.target.value),
                    name: "role",
                  }}
                />
              </Grid>
            </Grid>

            <Grid container spacing={2}>
              <Grid item xs={12} className={classes.inputContainer}>
                <CustomInput
                  labelText="GitHub URL"
                  id={`projectGithubUrl-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: project.githubUrl,
                    onChange: (e) => handleProjectChange(index, 'githubUrl', e.target.value),
                    name: "githubUrl",
                  }}
                />
              </Grid>
            </Grid>

            <Grid container spacing={2} style={{ marginTop: '10px' }}>
              <Grid item xs={6}>
                <CustomInput
                  labelText="Start Date (MM/YYYY)"
                  id={`projectStartDate-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: project.startDate,
                    onChange: (e) => handleDateChange(index, e),
                    name: "startDate",
                    placeholder: "MM/YYYY"
                  }}
                />
              </Grid>
              <Grid item xs={6}>
                <CustomInput
                  labelText="End Date (MM/YYYY)"
                  id={`projectEndDate-${index}`}
                  formControlProps={{ fullWidth: true }}
                  inputProps={{
                    value: project.endDate,
                    onChange: (e) => handleDateChange(index, e),
                    name: "endDate",
                    placeholder: "MM/YYYY"
                  }}
                />
              </Grid>
            </Grid>

            {/* Tech Stack Input and Chips */}
            <TextField
              label="Tech Stack (Enter tech stack separated by commas)"
              variant="outlined"
              fullWidth
              value={project.techStack}
              onChange={(e) => handleProjectTechStackChange(index, e)} 
              margin="normal"
              id={`projectTechStack-${index}`}
            />
            <div className={classes.chipContainer}>
              {project.techStack.split(',').map((tech, i) => (
                <Chip key={i} label={tech.trim()} className={classes.chip} />
              ))}
            </div>

            {/* Points Section (2 Fixed Points) */}
            <div className={classes.pointContainer}>
              {Array.from({ length: 2 }, (_, pointIndex) => ( 
                <div key={pointIndex} className={classes.pointInput}>
                  <span className={classes.bulletPoint}>•</span>
                  <CustomInput
                    labelText="What you did"
                    id={`projectWhat-${index}-${pointIndex}`}
                    formControlProps={{ fullWidth: true }}
                    inputProps={{
                      name: `what-${pointIndex}`, 
                      value: project.points[pointIndex]?.what || '',
                      onChange: (event) => handlePointChange(index, pointIndex, 'what', event.target.value),
                    }}
                  />
                  <CustomInput
                    labelText="Impact it created"
                    id={`projectImpact-${index}-${pointIndex}`}
                    formControlProps={{ fullWidth: true }}
                    inputProps={{
                      name: `impact-${pointIndex}`, 
                      value: project.points[pointIndex]?.impact || '',
                      onChange: (event) => handlePointChange(index, pointIndex, 'impact', event.target.value),
                    }}
                  />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      ))}
      {projects.length < 3 && (
        <Button
          color="primary"
          onClick={addProject}
          className={classes.addButton}
        >
          Add Project
        </Button>
      )}
    </div>
  );
}

My experience has dynamic points. But my project/github has fixed 2 points. This is causing a messy situation in my percentage calculation. I tried various methods through all LLMs, but it keeps getting messier. 

So I want this fix:
The percentage completition should expect 1 point to be filled per experience or per project. Forget dynamic and forget 2 points. Just 1 point for each of the newly added projects, or experiences. If the user fills that one point (both what and impact), then profile is complete. This gets us out of the mess we have made here.