/**
 * テストページコンポーネント
 * 白紙の状態で表示されるテスト用のページ
 */
import React, { useState, useEffect } from 'react';
import { stockApi } from '../services/api';
import { Stock } from '../types/types';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from "@mui/material";
import {
    Container,
    Typography,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    TextField,
    Button,
    Box,

} from '@mui/material';
import { TASK_ERRORS } from '../constants/errorMessages';
import CategoryDropDown from "../components/CategoryDropDown";

const StockPage: React.FC = () => {

    const [stocks, setStocks] = useState<Stock[]>([]);
    // 在庫編集ダイアログの表示状態
    const [openDialog, setOpenDialog] = useState(false);

    // コンポーネントマウント時にタスク一覧を取得
    useEffect(() => {
        fetchStocks();
    }, []);

    /**
     * APIからタスク一覧を取得する関数
     * 取得したタスクをstate(tasks)に設定
     */
    const fetchStocks = async () => {
        try {
            const stocks = await stockApi.getStocks();
            setStocks(stocks.stock_array);
        } catch (error) {
            console.error(`${TASK_ERRORS.FETCH_FAILED}:`, error);
        }
    };

    /**
     * 文字列(ISO 8601形式)をyyyy/MM/ddに変換する関数
     */
    const formatDate = (isoString: string): string => {
        const date = new Date(isoString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月は0始まりなので+1
        const day = date.getDate().toString().padStart(2, "0");
        return `${year}/${month}/${day}`;
    };
    /* Date型をyyyy/MM/ddに変換する関数
    const formatDate = (date: Date): string => {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月は0始まりなので+1
        const day = date.getDate().toString().padStart(2, "0");
        return `${year}/${month}/${day}`;
    };
    */

    return (
        <Container>
            <Typography variant="h4" component="h1" gutterBottom>
                在庫一覧
            </Typography>

            {/* タスク編集ボタン */}
            <Button color="success"
                type="submit"
                variant="contained"
                sx={{ mt: 3, mb: 2, left: '80%' }}
            >
                編集
            </Button>

            {/* タスク削除ボタン */}
            <Button color="error"
                type="submit"
                variant="contained"
                sx={{ mt: 3, mb: 2, left: '82%' }}
            >
                削除
            </Button>

            <Typography variant="h4" component="h1" gutterBottom>
                乳製品
            </Typography>
            {/* 乳製品一覧表示エリア - 青い背景のコンテナ */}
            <div style={{ border: '3px solid black', borderRadius: '8px', backgroundColor: '#add8e6', height: 'auto', padding: '20px', marginBottom: "20px" }}>

                {/* 要素が無かったら表示しない */}
                {stocks.filter(stock => stock.category === "乳製品").length === 0 ? null : (
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead sx={{ backgroundColor: "#dcdcdc", color: "#333" }}>
                                <TableRow>
                                    <TableCell>食材名</TableCell>
                                    <TableCell>数量</TableCell>
                                    <TableCell>購入価格</TableCell>
                                    <TableCell>賞味・消費期限</TableCell>
                                    <TableCell>購入日</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {stocks
                                    .filter(stock => stock.category == "乳製品") // 乳製品だけ抽出
                                    .map(stock => (
                                        <TableRow key={stock.stock_id}
                                        >
                                            <TableCell>{stock.stuff_name}</TableCell>
                                            <TableCell>{stock.amount}</TableCell>
                                            <TableCell>{stock.price}</TableCell>
                                            <TableCell>{formatDate(stock.exp_date)}</TableCell>
                                            <TableCell>{formatDate(stock.buy_date)}</TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </div>

            <Typography variant="h4" component="h1" gutterBottom>
                肉・魚
            </Typography>
            {/* 肉・魚一覧表示エリア - 青い背景のコンテナ */}
            <div style={{ border: '3px solid black', borderRadius: '8px', backgroundColor: '#add8e6', height: 'auto', padding: '20px', marginBottom: "20px" }}>

                {stocks.filter(stock => stock.category == "肉" || stock.category == "魚").length === 0 ? null : (
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead sx={{ backgroundColor: "#dcdcdc", color: "#333" }}>
                                <TableRow>
                                    <TableCell>食材名</TableCell>
                                    <TableCell>数量</TableCell>
                                    <TableCell>購入価格</TableCell>
                                    <TableCell>賞味・消費期限</TableCell>
                                    <TableCell>購入日</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {stocks
                                    .filter(stock => stock.category == "肉" || stock.category == "魚") // 肉と魚だけ抽出
                                    .map(stock => (
                                        <TableRow key={stock.stock_id}>
                                            <TableCell>{stock.stuff_name}</TableCell>
                                            <TableCell>{stock.amount}</TableCell>
                                            <TableCell>{stock.price}</TableCell>
                                            <TableCell>{formatDate(stock.exp_date)}</TableCell>
                                            <TableCell>{formatDate(stock.buy_date)}</TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}

            </div>

            <Typography variant="h4" component="h1" gutterBottom>
                野菜
            </Typography>
            {/* 野菜一覧表示エリア - 青い背景のコンテナ */}
            <div style={{ border: '3px solid black', borderRadius: '8px', backgroundColor: '#add8e6', height: 'auto', padding: '20px', marginBottom: "20px" }}>
                {stocks.filter(stock => stock.category === "野菜").length === 0 ? null : (
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead sx={{ backgroundColor: "#dcdcdc", color: "#333" }}>
                                <TableRow>
                                    <TableCell>食材名</TableCell>
                                    <TableCell>数量</TableCell>
                                    <TableCell>購入価格</TableCell>
                                    <TableCell>賞味・消費期限</TableCell>
                                    <TableCell>購入日</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {stocks
                                    .filter(stock => stock.category == "野菜") // 野菜だけ抽出
                                    .map(stock => (
                                        <TableRow key={stock.stock_id}>
                                            <TableCell>{stock.stuff_name}</TableCell>
                                            <TableCell>{stock.amount}</TableCell>
                                            <TableCell>{stock.price}</TableCell>
                                            <TableCell>{formatDate(stock.exp_date)}</TableCell>
                                            <TableCell>{formatDate(stock.buy_date)}</TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </div>

            <Typography variant="h4" component="h1" gutterBottom>
                調味料
            </Typography>
            {/* 調味料一覧表示エリア - 青い背景のコンテナ */}
            <div style={{ border: '3px solid black', borderRadius: '8px', backgroundColor: '#add8e6', height: 'auto', padding: '20px', marginBottom: "20px" }}>
                {stocks.filter(stock => stock.category === "調味料").length === 0 ? null : (
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead sx={{ backgroundColor: "#dcdcdc", color: "#333" }}>
                                <TableRow>
                                    <TableCell>食材名</TableCell>
                                    <TableCell>数量</TableCell>
                                    <TableCell>購入価格</TableCell>
                                    <TableCell>賞味・消費期限</TableCell>
                                    <TableCell>購入日</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {stocks
                                    .filter(stock => stock.category == "調味料") // 調味料だけ抽出
                                    .map(stock => (
                                        <TableRow key={stock.stock_id}>
                                            <TableCell>{stock.stuff_name}</TableCell>
                                            <TableCell>{stock.amount}</TableCell>
                                            <TableCell>{stock.price}</TableCell>
                                            <TableCell>{formatDate(stock.exp_date)}</TableCell>
                                            <TableCell>{formatDate(stock.buy_date)}</TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </div>

            <Typography variant="h4" component="h1" gutterBottom>
                その他
            </Typography>
            {/* その他一覧表示エリア - 青い背景のコンテナ */}
            <div style={{ border: '3px solid black', borderRadius: '8px', backgroundColor: '#add8e6', height: 'auto', padding: '20px', marginBottom: "20px" }}>
                {stocks.filter(stock => stock.category === "その他").length === 0 ? null : (
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead sx={{ backgroundColor: "#dcdcdc", color: "#333" }}>
                                <TableRow>
                                    <TableCell>食材名</TableCell>
                                    <TableCell>数量</TableCell>
                                    <TableCell>購入価格</TableCell>
                                    <TableCell>賞味・消費期限</TableCell>
                                    <TableCell>購入日</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {stocks
                                    .filter(stock => stock.category == "その他") // その他だけ抽出
                                    .map(stock => (
                                        <TableRow key={stock.stock_id}>
                                            <TableCell>{stock.stuff_name}</TableCell>
                                            <TableCell>{stock.amount}</TableCell>
                                            <TableCell>{stock.price}</TableCell>
                                            <TableCell>{formatDate(stock.exp_date)}</TableCell>
                                            <TableCell>{formatDate(stock.buy_date)}</TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </div>
        </Container>
    );
};

export default StockPage;