import { useEffect, useState } from 'react';
import Upload from './Upload';
import ChatApi from './ChatApi';
import TwoColumnLayout from './layout/TwoColumn';
import OpportunityForm from './OpportunityForm';
import { Button } from './ui/button';

const Opportunities = () => {

  const [opportunities, setOpportunities] = useState([]);
  const [selectedOpportunity, setSelectedOpportunity] = useState(null);
  const [token, setToken] = useState(null);
  const [research, setResearch] = useState(null);
  
  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    console.log('storedToken*******', storedToken)

    fetch('/api/opportunities', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${storedToken}`,
        'Content-Type': 'application/json'
      }
    }).then(response => response.json())
      .then(data => {

        console.log('data.records*******', data.success && data.data.records?.length > 0)
        if (data.success && data.data.records?.length > 0) {
          setOpportunities(data.data.records);
        }
        
        setToken(storedToken);
      })
    console.log('storedToken', storedToken)
  }, [])

  const handleLogout = () => {
    localStorage.removeItem('token');
    location = '/'
  };

  const customerResearch = (opportunity) => {
    fetch('/api/customer_insights', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: opportunity['opportunityName']
      })
    }).then(response => response.json())
      .then(data => {
        console.log('data*******', data)
      })
  }

  return (
    <>
      <TwoColumnLayout tabs={['Opportunities', 'New Opportunity']}>
          <ChatApi />
          <div className="flex flex-col h-[calc(89vh-7px)]">
            {opportunities.map((opportunity, id) => (
              <Button key={id} onClick={() => setSelectedOpportunity(opportunity)}>{opportunity.opportunityName}</Button>
            ))}
            <div className="flex-1 overflow-y-auto p-4 space-y-4 h-[80vh]">
              {Object.keys(selectedOpportunity || {}).map((key, index) => (
                <div key={key+'-'+index}>{key}: {selectedOpportunity[key]}</div>
              ))}
              {research && <div>{research}</div>}
            </div>

            <div className="p-4 bg-white border-t">
             <Button style={{'marginRight':'10px'}} onClick={() => {customerResearch(selectedOpportunity); setResearch(null)}}>Prism</Button>
              <Button style={{'marginRight':'10px'}}>Scout</Button>
              <div style={{'float':'right'}}><Upload token={token} /></div>
            </div>
          </div>
          <OpportunityForm/>
      </TwoColumnLayout>
      {/*
      <div className="min-h-screen bg-gray-100 dark:bg-gray-900 flex flex-col">
        <div className="flex-1 overflow-auto p-6">
          <h2 style={{ 'fontSize': 'revert' }}>Opportunities</h2>
          <table className="border-collapse border border-slate-400" style={{fontSize:"12px"}}>
            <thead><tr>{Object.keys(opportunities[0] || []).map((e, index) => <td key={'thead-r-'+index}>{e}</td>)}</tr></thead>
          {opportunities.map((opportunity, id) => (
            <tbody key={id}>
            <tr>
             {Object.keys(opportunity).map((key, index) => (
               <td key={key+'-'+index} className="border border-slate-400 p-2">{opportunity[key]}</td>
             ))}
            </tr>
            </tbody>
          ))}
          </table>
        </div>
        <div className="border-t p-4 bg-white dark:bg-gray-800">
          <div className="flex items-center space-x-2">
            <Chat />
            <Upload token={token} />
            <button onClick={handleLogout} className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400">Logout</button>
          </div>
        </div>
      </div>*/}
    </>
  )
}


export default Opportunities;