import React, { useState, ChangeEvent, FormEvent, Dispatch, useEffect } from 'react';
import {
    Box,
    Button,
    Collapse,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    TextField,
    Checkbox,
    FormControlLabel,
    Paper,
    Typography,
    RadioGroup,
    Radio,
    Stack,
    Autocomplete,
} from '@mui/material';
import { SelectChangeEvent } from '@mui/material/Select';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import { useTranslation } from 'react-i18next';
import { Controller, useFormContext } from 'react-hook-form';
import { EscalationInput, ModalFormInput } from '@/app/api/stockIn/index';
import { EscalationCombo } from "@/app/api/user";
import { fetchEscalationCombo } from "@/app/api/user/actions";
import { FireExtinguisher } from '@mui/icons-material';

interface NameOption {
    value: string;
    label: string;
}

interface FormData {
    name: string;
    quantity: string;
    message: string;
}

interface Props {
    forSupervisor: boolean
    isCollapsed: boolean
    setIsCollapsed: Dispatch<React.SetStateAction<boolean>>
    // escalationCombo: EscalationCombo[]
}

const EscalationComponent: React.FC<Props> = ({
    forSupervisor,
    isCollapsed,
    setIsCollapsed,
    // escalationCombo
}) => {
    const { t } = useTranslation("purchaseOrder");

    const [formData, setFormData] = useState<FormData>({
        name: '',
        quantity: '',
        message: '',
    });

    const [escalationCombo, setEscalationCombo] = useState<EscalationCombo[]>([]);

    useEffect(() => {
        async function fetchData() {
            if (escalationCombo.length < 1) {
            const escCombo = await fetchEscalationCombo();
            setEscalationCombo(escCombo);
            }
        }
        fetchData();
    }, [])

    const {
        register,
        formState: { errors, defaultValues, touchedFields },
        watch,
        control,
        setValue,
        getValues,
        reset,
        resetField,
        setError,
        clearErrors,
    } = useFormContext<ModalFormInput>();

    const handleInputChange = (
        event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement> | SelectChangeEvent<string>
    ): void => {
        const { name, value } = event.target;
        setFormData((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    const handleSubmit = (e: FormEvent<HTMLFormElement>): void => {
        console.log("Handled Submit?");
        e.preventDefault();
        console.log('表單已提交:', formData);
        // 處理表單提交
    };

    const handleCollapseToggle = (e: ChangeEvent<HTMLInputElement>): void => {
        setIsCollapsed(e.target.checked);
    };

    return (
        // <Paper elevation={3} sx={{ maxWidth: 400, mx: 'auto', p: 3 }}>
        <>
            <Paper sx={{ padding: 2 }}>
                {/* <Paper elevation={3} sx={{ mx: 'auto', p: 3 }}> */}
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Typography variant="body1">上報結果</Typography>
                        {/* {isCollapsed ? (
                            <ExpandLessIcon sx={{ ml: 1 }} />
                        ) : (
                            <ExpandMoreIcon sx={{ ml: 1 }} />
                        )} */}
                    </Box>
                    {/* <FormControlLabel
                    control={
                        <Checkbox
                            checked={isCollapsed}
                            onChange={handleCollapseToggle}
                            color="primary"
                        />
                    }
                    label={
                        <Box sx={{ display: 'flex', alignItems: 'center' }}>
                            <Typography variant="body1">上報結果</Typography>
                            {isCollapsed ? (
                                <ExpandLessIcon sx={{ ml: 1 }} />
                            ) : (
                                <ExpandMoreIcon sx={{ ml: 1 }} />
                            )}
                        </Box>
                    }
                /> */}
                </Box>
                <Collapse in={isCollapsed}>
                    <Box component="form" onSubmit={handleSubmit} sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        <FormControl fullWidth>
                            <Controller
                                control={control}
                                name="escalationLog.handlerId"
                                render={({field, fieldState, formState}) => {
                                    return (<Autocomplete
                                        noOptionsText={t("No Option")}
                                        disableClearable
                                        fullWidth
                                        // value={}
                                        // {...register("escalationLog.handlerId", {
                                        //     required: "handler required!",
                                        // })}
                                        // onChange={() => handleInputChange}
                                        onChange={(event, value) => {
                                            field.onChange(value.id);
                                        }}
                                        // getOptionLabel={(option) => option.label}
                                        options={escalationCombo}
                                        renderInput={(params) => <TextField {...params} error={false} label={"負責處理同事"}/>}
                                    />)
                                }}

                            />
                            {/* <select
                            id="handlerId"
                            // name="name"
                            // value={formData.name}
                            {...register("escalationLog.handlerId", {
                                required: "handler required!",
                            })}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
                        >
                            {nameOptions.map((option: NameOption) => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select> */}
                        </FormControl>
                        {forSupervisor ? (
                            <FormControl>
                                <RadioGroup
                                    row
                                    aria-labelledby="demo-radio-buttons-group-label"
                                    defaultValue="pass"
                                    name="radio-buttons-group"
                                >
                                    <FormControlLabel value="pass" control={<Radio />} label="合格" />
                                    <FormControlLabel value="fail" control={<Radio />} label="不合格" />
                                </RadioGroup>
                            </FormControl>
                        ) : undefined}
                        {forSupervisor && (<TextField
                            fullWidth
                            id="decision"
                            name="decision"
                            label="上報結果"
                            type="radio"
                            // value={formData.decision}
                            onChange={handleInputChange}
                            InputProps={{ inputProps: { min: 1 } }}
                            placeholder="請決定上報結果"
                        />)}
                        {/* <TextField
                        fullWidth
                        id="quantity"
                        name="quantity"
                        label="數量"
                        type="number"
                        value={formData.quantity}
                        onChange={handleInputChange}
                        InputProps={{ inputProps: { min: 1 } }}
                        placeholder="請輸入數量"
                    /> */}

                        <TextField
                            fullWidth
                            id="reason"
                            // name="reason"
                            {...register("escalationLog.reason", {
                                required: "請輸入上報原因",
                            })}
                            label="上報原因"
                            multiline
                            rows={4}
                            // value={formData.reason}
                            onChange={handleInputChange}
                            placeholder="請輸入上報原因"
                            error={Boolean(errors.escalationLog?.reason)}
                            helperText={errors.escalationLog?.reason?.message}
                        />

                        {/* <Stack direction="row" justifyContent="flex-end" gap={1}>
                        <Button
                            type="submit"
                            variant="contained"
                            color="primary"
                        >
                            {t("update qc info")}
                        </Button>
                    </Stack> */}
                    </Box>
                </Collapse>
            </Paper>
        </>
    );
}

export default EscalationComponent;