"use client";

import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useTranslation } from "react-i18next";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import Link from "next/link";
import React, { SyntheticEvent, useCallback, useMemo, useState } from "react";
import MailField from "../MailField/MailField";
import { MailSave } from "@/app/api/mail/actions";
import { MailTemplate } from "@/app/api/mail";
import { isEmpty, keys } from "lodash";
import { Autocomplete, ListSubheader, MenuItem, UseAutocompleteProps } from "@mui/material";

interface Props {
    isActive: boolean;
}

interface OptionType {
    value: number,
    label: string,
    group: string,
}

type fieldKeys = keyof MailTemplate

const TemplateDetails: React.FC<Props> = ({ isActive }) => {
    const { t } = useTranslation();

    // const disabledFields: fieldKeys[] = []
    // const requiredFields: fieldKeys[] = []
    // const skipFields: fieldKeys[] = ["code", "subjectEng", "contentEng"]
    const [selectedIndex, setSelectedIndex] = useState(0)

    const {
        register,
        formState: { errors },
        control,
        watch,
        getValues
    } = useFormContext<MailSave>();

    const {
        fields,
    } = useFieldArray({
        control,
        name: "templates"
    })

    const options: OptionType[] = useMemo(() => (
        fields.map((field, index) => {
            return {
                value: index,
                label: `${field.code} - ${field.description}`,
                group: field.type
            } as OptionType
        })
    ), [fields])

    const makeAutocompleteChangeHandler = useCallback(() => {
        return (e: SyntheticEvent, newValue: OptionType) => {
            setSelectedIndex(() => newValue.value);
        };
    }, []);

    // const renderFieldsBySwitchCases = useCallback(() => {
    //     const fieldNames = keys(fields[0]) as fieldKeys[];

    //     return fieldNames
    //         .filter((name) => !skipFields.includes(name))
    //         .map((name: fieldKeys, index: number) => {
    //             switch (name) {
    //                 case "contentCht":
    //                     return (
    //                         <Grid item xs={12}>
    //                             <Controller
    //                                 control={control}
    //                                 name={`templates.${selectedIndex}.contentCht`}
    //                                 render={({ field }) => (
    //                                     <MailField
    //                                         content={field.value}
    //                                         onChange={field.onChange}
    //                                         error={Boolean(errors.templates?.[selectedIndex]?.contentCht)}
    //                                     />
    //                                 )}
    //                                 rules={{
    //                                     required: requiredFields.includes(name),
    //                                 }}
    //                             />
    //                         </Grid>
    //                     )
    //                 default:
    //                     return (
    //                         <Grid item xs={8}>
    //                             <TextField
    //                                 label={t(name)}
    //                                 fullWidth
    //                                 {...register(`templates.${selectedIndex}.cc`),
    //                                 {
    //                                     required: requiredFields.includes(name)
    //                                 }}
    //                             />
    //                         </Grid>
    //                     )
    //             }
    //         })
    // }, [fields])

    return (
        <Card sx={{ display: isActive ? "block" : "none" }}>
            <CardContent component={Stack} spacing={4}>
                <Box>
                    <Typography variant="overline" display="block" marginBlockEnd={1}>
                        {t("Template")}
                    </Typography>
                    <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
                        <Grid item xs={8}>
                            <Autocomplete
                                disableClearable
                                options={options}
                                value={options[selectedIndex]}
                                onChange={makeAutocompleteChangeHandler}
                                groupBy={(option) => (
                                    option.group && option.group.trim() !== '' ? option.group : 'Ungrouped'
                                )}
                                renderGroup={(params) => (
                                    <React.Fragment>
                                        <ListSubheader>{params.group}</ListSubheader>
                                        {params.children}
                                    </React.Fragment>
                                )}
                                renderOption={(
                                    params: React.HTMLAttributes<HTMLLIElement> & { key?: React.Key },
                                    option,
                                    { selected },
                                ) => {
                                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                                    const { key, ...rest } = params;
                                    return (
                                        <MenuItem
                                            {...rest}
                                            disableRipple
                                            value={option.value}
                                        >
                                            {option.label}
                                        </MenuItem>
                                    );
                                }}
                                renderInput={(params) => <TextField {...params} variant="outlined" label={t("Select Template (View By Code - Description)")} />}
                            />
                        </Grid>
                        <Grid item xs={8}>
                            <TextField
                                label={t("Code")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.code`, {
                                    required: "Code is required!"
                                })}
                                required
                                error={Boolean(errors.templates?.[selectedIndex]?.code)}
                            />
                        </Grid>
                        <Grid item xs={8}>
                            <TextField
                                label={t("Description")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.description`, {
                                    required: "Description is required!"
                                })}
                                required
                                error={Boolean(errors.templates?.[selectedIndex]?.description)}
                            />
                        </Grid>
                        {/* <Grid item xs={8}>
                            <TextField
                                label={t("To")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.to`, {
                                    required: "To is required!"
                                })}
                                required
                                error={Boolean(errors.templates?.[selectedIndex]?.to)}
                            />
                        </Grid>
                        <Grid item xs={8}>
                            <TextField
                                label={t("Cc")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.cc`)}
                            />
                        </Grid>
                        <Grid item xs={8}>
                            <TextField
                                label={t("Required Params (split by ',')")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.params`)}
                            />
                        </Grid> */}
                        <Grid item xs={8}>
                            <TextField
                                label={t("Subject CHT")}
                                fullWidth
                                {...register(`templates.${selectedIndex}.subjectCht`,
                                    {
                                        required: "Mail Subject is required!",
                                    })}
                                required
                                error={Boolean(errors.templates?.[selectedIndex]?.subjectCht)}
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <Controller
                                control={control}
                                name={`templates.${selectedIndex}.contentCht`}
                                render={({ field }) => (
                                    <MailField
                                        content={field.value}
                                        onChange={field.onChange}
                                        error={Boolean(errors.templates?.[selectedIndex]?.contentCht)}
                                    />
                                )}
                                rules={{
                                    required: "Mail Content is required!",
                                }}
                            />
                        </Grid>
                    </Grid>
                </Box>
            </CardContent>
        </Card>
    );
};

export default TemplateDetails;
