
import React,{Component} from 'react';
import axios from 'axios';
import { useState,useEffect } from "react";
import {Link} from 'react-router-dom';
import Wallet from './Wallet';
import { confirmAlert } from 'react-confirm-alert';
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css

export default function MyOrders (){
    
    const [orders,setOrders]=useState([]);
    const [porders,setPorders]=useState([]);
    const [corders,setCorders]=useState([]);
    const [inputField , setInputField] = useState({target:'',stoploss:'',trdid:''});
    const handleChange = (e) =>{
        const value = e.target.value;
        setInputField({
            ...inputField,
            [e.target.name]: value
        });
    }
    const trdSqoff=(tid)=>{
        fetch('https://capitalsgrowth.in/Rest/square_off_api/'+tid).then((response)=>response.json())
        .then((responseJson)=>{
            alert(responseJson.msg);
            //console.log(responseJson);
        }).catch((error)=>{
          console.log(error)
        });
    }

    const editTrade=(tid)=>{
        fetch('https://capitalsgrowth.in/Rest/edit_trade_api/'+tid).then((response)=>response.json())
        .then((responseJson)=>{
            //alert(responseJson.msg);
            //console.log(responseJson);
            setInputField({ ...inputField,target: responseJson.target,stoploss:responseJson.stoploss,trdid:tid})
        }).catch((error)=>{
          console.log(error)
        });
    }

    const formSubmit = param => e => {e.preventDefault(); 
        axios.post('https://capitalsgrowth.in/Rest/update_trade_api/',{target:inputField.target,stoploss:inputField.stoploss,bsid:inputField.trdid})
            .then((res) => {
            //console.log(res.data);return false;
            alert(res.data.msg);            
        }).catch((err) => alert("Error start trading"));    
    }

    const pendingOrds=()=>{
        var userid= localStorage.getItem('userid');
        fetch('https://capitalsgrowth.in/Rest/pending_ord_api/'+userid).then((response)=>response.json())
        .then((responseJson)=>{
            setPorders(responseJson);
            //console.log(responseJson);
        }).catch((error)=>{
          console.log(error)
        });
    }

    const compOrds=()=>{
        var userid= localStorage.getItem('userid');
        fetch('https://capitalsgrowth.in/Rest/exit_trades_api/'+userid).then((response)=>response.json())
        .then((responseJson)=>{
            setCorders(responseJson);
           // console.log(responseJson);
        }).catch((error)=>{
          console.log(error)
        });
    }
    
    useEffect(() => {
        var userid= localStorage.getItem('userid');
        const interval = setInterval(() => {
            fetch('https://capitalsgrowth.in/Rest/my_trades_api/'+userid).then((response)=>response.json())
            .then((responseJson)=>{
              // console.log(responseJson);
               setOrders(responseJson);
            }).catch((error)=>{
              console.log(error)
            });
        }, 1000);
        return () => clearInterval(interval);
      }, []);

      const setDelivery=(id)=>{
        const urls='https://capitalsgrowth.in/Rest/set_delivery_api/'+id;
          fetch(urls).then((response)=>response.json())
          .then((responseJson)=>{
            
          }).catch((error)=>{
            console.log(error)
        });
      }

      const intraSet=(id)=>{
        const urls='https://capitalsgrowth.in/Rest/set_intraday_api/'+id;
          fetch(urls).then((response)=>response.json())
          .then((responseJson)=>{
          }).catch((error)=>{
            console.log(error)
        });
      }

        return (     
            <>
            

<div className="section mt-1">
    <div className="card">
        <div className="card-body pt-0">
            <ul className="nav nav-tabs lined" role="tablist">
                <li className="nav-item">
                    <a className="nav-link active" data-bs-toggle="tab" href="#overview2" role="tab">
                        ACTIVE
                    </a>
                </li>
                <li className="nav-item">
                    <a onClick={()=>pendingOrds()} className="nav-link" data-bs-toggle="tab" href="#cards2" role="tab">
                        PENDING
                    </a>
                </li>
                <li className="nav-item">
                    <a onClick={()=>compOrds()} className="nav-link" data-bs-toggle="tab" href="#settings2" role="tab">
                        CLOSED
                    </a>
                </li>
            </ul>
            <div className="tab-content mt-2">
                <div className="tab-pane fade show active" id="overview2" role="tabpanel">
                {orders.map(m => (
                    <div className='row'>
                        <div className='col-4'>
                            <small>{m.type} {m.lotsize}</small>
                            <h4>{m.metal}</h4>
                            <small>STL-{m.stoploss}&nbsp; TGT-{m.target}</small>
                        </div>
                        <div className='col-4 text-center'>
                            <small>LTP</small>
                            <h4>{m.last_live}</h4>
                            <small>LIMIT {m.setlimit}</small><br/>
                            {m.holding!='On' &&
                            <div>
                      {/* <img width="30px" onClick={()=>setDelivery(m.bsid)} src="/site/intraday.png"/>&nbsp; */}
                  
                  {m.del_req!='' &&
                  <small className='text-success'>RQST</small>}
                  </div>}
                  {m.holding=='On' &&
                      <img width="30px" onClick={()=>intraSet(m.bsid)} src='/site/delivery.png'/>}&nbsp;
                       {m.holding=='On' &&
                    <small className='text-danger'>HOLD</small>}
                        </div>
                        <div className='col-4 float-right text-right' style={{textAlign:'right'}}>
                            <small>Profit/Loss</small><br/>
                            {m.pro_loss>0 &&
                            <h4 className='text-success'>{m.pro_loss}</h4>}                            
                            {m.pro_loss<0 &&
                            <h4 className='text-danger'>{m.pro_loss}</h4>}
                            {m.sq_off!='On' && m.holding!='On' && 
                            <button type="button" onClick={()=>trdSqoff(m.bsid)}  className='btn btn-sm btn-danger mt-1'>SQROFF</button>}
                            &nbsp;
                            <a href="#" data-bs-toggle="modal" data-bs-target="#ModalBasic"
                             onClick={()=>editTrade(m.bsid)}  className='btn btn-sm btn-warning mt-1'>EDIT</a>
                        </div>
                    </div>))}
                </div>
                <div className="tab-pane fade" id="cards2" role="tabpanel">
                {porders.map(m => (
                    <div className='row' >
                        <div className='col-4'>
                            <small>{m.type} {m.lotsize}</small>
                            <h4>{m.metal}</h4><small>STL {m.stoploss}</small> &nbsp;&nbsp;
                            <small>TGT {m.target}</small>
                        </div>
                        <div className='col-4 text-center'>
                            <small>LTP</small>
                            <h4>{m.last_live}</h4>
                            <small>LIMIT {m.setlimit}</small>
                        </div>
                        <div className='col-4 float-right text-right'  style={{textAlign:'right'}}>
                            <small>Profit/Loss</small>
                            {m.pro_loss>0 &&
                            <h4 className='text-success'>{m.pro_loss}</h4>}                            
                            {m.pro_loss<0 &&
                            <h4 className='text-danger'>{m.pro_loss}</h4>}
                        </div>
                    </div>))}
                </div>
                <div className="tab-pane fade" id="settings2" role="tabpanel">
                {corders.map(m => (
                    <div className='row' >
                        <div className='col-4'>
                            <small>{m.type} {m.lotsize}</small>
                            <h4>{m.metal}</h4>
                            <small>STL {m.stoploss}</small> &nbsp;&nbsp;
                            <small>TGT {m.target}</small>
                        </div>
                        <div className='col-4 text-center'>
                            <small>LTP</small>
                            <h4>{m.last_live}</h4>
                            <small>LIMIT {m.setlimit}</small>
                        </div>
                        <div className='col-4 float-right text-right'  style={{textAlign:'right'}}>
                            <small>Profit/Loss</small>
                            {m.pro_loss>0 &&
                            <h4 className='text-success'>{m.pro_loss}</h4>}                            
                            {m.pro_loss<0 &&
                            <h4 className='text-danger'>{m.pro_loss}</h4>}
                        </div>
                    </div>))}
                </div>
            </div>
        </div>
    </div>
</div>
<div className="modal fade modalbox" id="ModalBasic" tabindex="-1" role="dialog">
            <div className="modal-dialog" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title">Edit Trade</h5>
                        <a href="#" data-bs-dismiss="modal">Close</a>
                    </div>
                    <div className="modal-body">
                        <div className="form-group basic">
                            <div className="input-wrapper">
                                <label className="label" for="email1">Target</label>
                                <input type="number" name="target" value={inputField.target} onChange={handleChange} 
                                 className="form-control" placeholder=""/>
                            </div>
                        </div>

                        <div className="form-group basic">
                            <div className="input-wrapper">                            
                                <label className="label" for="email1">Stoploss</label>
                                <input type="number" name="stoploss" value={inputField.stoploss} onChange={handleChange} 
                                 className="form-control" placeholder=""/>
                            </div>
                        </div>
                        <button type='button' onClick={formSubmit()} className="btn btn-lg btn-danger btn-block">UPDATE</button>
                    </div>
                </div>
            </div>
        </div>
            </> 
        );
    }



