import React from 'react';
import axios from 'axios';
import { useState,useEffect } from "react";
import { useParams,Link, useNavigate} from 'react-router-dom';
import { Helmet } from 'react-helmet';

export default function AddTrade(props){
    const navigate = useNavigate();
    
    const { metal } = useParams('metal');
    const [btn1,setBtn1]=useState('primary');
    const [btn2,setBtn2]=useState('outline-primary');
    //const [otype,setOtype]=useState('normal');
    const [market,setMarket]=useState(true);
    const [formvals,setFormvals]=useState({lot:1,limit:'',stoploss:'',target:'',wpin:''});
    const [inputField , setInputField] = useState({rate:'',open:'',high:'',low:'',perchg:'',chg:'',otype:'normal',
    close:'',mtime:'',lotsize:1});

    const handleChange = (e) =>{
        const value = e.target.value;
        setFormvals({
            ...formvals,
            [e.target.name]: value
        });
    }
    
    const marketType = (v) => {
        console.log(v)
        setMarket(!market)
        if(v=='Market'){
            setBtn1('primary');
            setBtn2('outline-primary');
        }else{
            setBtn2('primary');
            setBtn1('outline-primary');
        }
     }

    const fetchData =()=>{
        const interval = setInterval(() => {
        fetch('https://capitalsgrowth.in/Rest/metal_api/'+metal)
        .then((response) =>{
            return response.json();
        }).then((data)=>{
            console.log(data.rate)
            setInputField({ ...inputField, rate: data.rate,high:data.high,low:data.low,close:data.close,open:data.open,
            chg:data.chg,perchg:data.perchg,lotsize:data.lots})
        });}, 1000);
        return () => clearInterval(interval);
    }
    useEffect(()=>{
        fetchData();
    },[])

    const tradeSubmit = param => e => {e.preventDefault();
        //console.log('param '+param);return false;
        //if(inputField.lot==''){alert("Please Enter Lot");return false;}
        var formData = new FormData();
        formData.append("market", market);
        formData.append("target", formvals.target);
        formData.append("stoploss", formvals.stoploss);
        formData.append("lotsize", formvals.lot);
        formData.append("limit", formvals.limit);
        formData.append("wpin", formvals.wpin);
        formData.append("asset", metal+'-'+inputField.lotsize);
        formData.append("userid", localStorage.getItem('userid'));
        formData.append("name", localStorage.getItem('name'));
        formData.append("buy_type", param);
        const config = {
            headers: {
              'content-type': 'multipart/form-data',
            },
          };
      
        axios.post('https://capitalsgrowth.in/Rest/web_trade_api', formData,config)
            .then((res) => {
           // console.log(res.data);
            //return false;
            alert(res.data.msg);
            if(res.data.status==0){
                navigate("/orders");
            }
        }).catch((err) => alert("Error start trading"));    
    }

        return (     
            <div>
            <Helmet>
            <title>MCX Trading</title>
            <link rel="stylesheet" href="/site/css/style.css"/>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/> 
            <script src="/site/js/lib/bootstrap.bundle.min.js"></script>
            <script src="/site/js/plugins/splide/splide.min.js"></script>
            
            </Helmet>
            
            <div className="appHeader no-border">
        <div className="left">
            <Link to="/dashboard" className="headerButton goBack">
                <i className="fa fa-arrow-left"></i> 
            </Link>
        </div>
        <div className="pageTitle">New Order</div>
        <div className="right"> </div>
    </div>
    <div id="appCapsule">
    
        <div className="section">
            
        <div className="transactions   pt-1 pb-1">
                <Link className="item">
                    <div className="detail">
                       <div>
                            <strong>{metal}</strong>
                            <p>O {inputField.open} H {inputField.high} L {inputField.low}</p>
                        </div>
                    </div>
                    <div className="right">
                        <div className="price text-danger">{inputField.rate}</div>                        
                        {inputField.chg>0 &&
                            <span className='badge badge-success'>chg {inputField.chg}</span>}
                            {inputField.chg<0 &&
                            <span className='badge badge-danger'>chg {inputField.chg}</span>}
                    </div>
                </Link></div>
        
            <div className="splash-page  pt-1 pb-1">
        
                
                <div className="btn-group">
                    <button type="button" onClick={()=>marketType('Market')} className={"btn btn-"+btn1}>MARKET</button>
                    {/* <button type="button" onClick={()=>marketType('Limit')} className={"btn btn-"+btn2}>LIMIT</button> */}
                </div><hr/>
                <div className='row'>
                    <div className='col-4'>
                        <div className="form-group basic">
                            <div className="input-wrapper">
                                <label className="label" for="email1">No of Lot</label>
                                <input type="number" name="lot" value={formvals.lot} onChange={handleChange}  className="form-control" placeholder="1-10"/>
                            </div>
                        </div>
                    </div>
                    {market==false &&
                    <div className='col-4'>
                        <div className="form-group basic">
                            <div className="input-wrapper">
                                <label className="label" for="email1">LIMIT</label>
                                <input type="number" name="limit" onChange={handleChange}  className="form-control" placeholder=""/>
                            </div>
                        </div>
                    </div>}

                    <div className='col-4'>
                        <div className="form-group basic">
                            <div className="input-wrapper">
                                <label className="label" for="email1">TARGET</label>
                                <input type="number" name="target" onChange={handleChange}  
                                className="form-control" />
                            </div>
                        </div>
                    </div>
                    <div className='col-4'>
                        <div className="form-group basic">
                            <div className="input-wrapper">
                                <label className="label" for="email1">STOPLOSS</label>
                                <input type="number" name="stoploss" onChange={handleChange}  className="form-control" 
                                placeholder=""/>
                            </div>
                        </div>
                    </div>
                    
                             
            </div>
            
        </div>
        {/* <div className="section full">
                    <div className="wide-block pt-1 pb-1">
                        <div className="form-check form-check-inline">
                            <input className="form-check-input" onChange={handleChange} value='normal' type="radio" name="otype"
                            checked={inputField.otype === "normal"}/>
                            <label className="form-check-label" for="normal"> Normal Order </label>
                        </div> &nbsp;&nbsp;&nbsp;
                        <div className="form-check form-check-inline">
                            <input className="form-check-input" onChange={handleChange} value='stoploss' type="radio" name="otype" 
                            checked={inputField.otype === "stoploss"}/>
                            <label className="form-check-label" for="stoploss"> Stoploss </label>
                        </div> 
                    </div>
                </div> */}
            </div>

        <div className="fixed-bar">
            <div className="row">
                <div className="col-6">
                    <button type='button' onClick={tradeSubmit('BUY')} className="btn btn-lg btn-danger btn-block">BUY</button>
                </div>
                <div className="col-6">
                    <button type='button' onClick={tradeSubmit('SELL')} className="btn btn-lg btn-success btn-block">SELL</button>
                </div>
            </div>
        </div>

    </div>
            </div>
        )
    }



