import Canva from './components/canvas';
import type { Route } from "./+types/home";
import { useState, useEffect, useRef } from 'react';
import { Link, Navigate, useLocation } from 'react-router';

export function meta({}: Route.MetaArgs) {
  return [
    { title: "detail" }
  ];
}


export default function Defail(){
    const DivStyle = {
        padding: '10px'
    }
    const BtnStyle = {
        padding: '10px',
        fontSize: '16px',
        borderRadius: '5px',
        border: '1px solid #ccc',
    }

    const [name, setName] = useState('')
    const [price, setPrice] = useState('')
    const [sale, setSale] = useState('')

    const canvasRef = useRef<HTMLCanvasElement>(null) 

    const location = useLocation()
    const metadata = location.state?.metadata

    if(!metadata){
        return <Navigate to="/" replace/>
    }

    useEffect(()=>{
        if(metadata){
            setName(metadata.name)
            setPrice(metadata.price)
            setSale(metadata.sale)
        }
    }, [metadata])

    async function handleClick(){
        const canvas = canvasRef.current
        if(!canvas){
            console.error("Canvas 元素尚未準備好。")
            return
        }
        
        const blob: Blob | null = await new Promise(resolve=>{
            if (canvas instanceof HTMLCanvasElement && typeof canvas.toBlob === 'function') {
                canvas.toBlob((blobResult)=>{
                    resolve(blobResult)
                }, 'image/png')
            } else {
                resolve(null);
            }
        })
        
        if(!blob){
            return
        }
        
        const formdata = new FormData()

        formdata.append('file', blob, '哈哈哈哈屁眼派對.png')
        formdata.append('name', name)
        formdata.append('price', price)
        formdata.append('sale', sale)
        
        const req = await fetch("https://bitmap-service.docker.orb.local/api/bitmap", { 
            method: 'POST',
            body: formdata,
        })
    }

    return (
        <>
        <Link to="/">Home</Link>
        <h1>Tag詳細資訊</h1>
        <div style={DivStyle}>
            <label>名稱: </label>
            <input type="text" style={BtnStyle} value={name} onChange={e=>{setName(e.target.value)}} />
        </div>
        <div style={DivStyle}>
            <label>售價: </label>
            <input type="number" style={BtnStyle} value={price} onChange={e=>{setPrice(e.target.value)}}/>
        </div>
        <div style={DivStyle}>
            <label>折扣: </label>
            <input type="text" style={BtnStyle} value={sale} onChange={e=>{setSale(e.target.value)}}/>
        </div>
        {/* Canva 組件必須使用 forwardRef 才能接收 ref */}
        <Canva name={name} price={price} ref={canvasRef}/>
        <br />
        <input type="button" value="送出" onClick={handleClick}/>
        </>
    )
}