import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import { Button, Grid, TextField, Typography, InputLabel, FormControl } from '@mui/material';
import Dialog from '@mui/material/Dialog';
import * as React from 'react';
import {useEffect, useRef, useState} from 'react';
import axios from 'axios';
import {apiPath, getUserData} from '../../../auth/utils';
import {useNavigate} from "react-router";
import AttachFileIcon from '@mui/icons-material/AttachFile'
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import { notifySaveSuccess, base64ToBlob } from "../../../utils/CommonFunction";
import { GET_TEMPLATE_PATH } from "../../../utils/ApiPathConst";


export function SelectTemplateWindow({ isWindowOpen, onNormalClose, onConfirmClose, clientId }) {
    const [errors, setErrors] = useState({});
    const [file, setFile] = React.useState(null)
    const [templateId, setTemplateId] = React.useState(0)
    const [templateList, setTemplateList] = React.useState([])
    const fileInputRef = useRef(null);
    const [currentView, setCurrentView] = useState('prefixSelection');
    const [selectedPrefix, setSelectedPrefix] = useState(null);
  
    const navigate = useNavigate()
  
    const handleOnClose = () => {
      onNormalClose();
    };

    useEffect(() => {
      axios.get(`${apiPath}${GET_TEMPLATE_PATH}`)
        .then((response) => {
          if (response.status === 200) {
            const record = response.data.records;
            // Group templates by their prefix
            const grouped = record.reduce((acc, template) => {
              const prefix = template.name.split(' ')[0];
              if (!acc[prefix]) {
                acc[prefix] = [];
              }
              //let's test ML first, so hide all SL forms
              //if(prefix != "SL")
              acc[prefix].push(template);
              return acc;
            }, {});
            setTemplateList(grouped); // Store the grouped data
          }
        })
        .catch(error => {
            console.log(error);
            return false;
        });
    }, []);
  
    const createNewForm = (templateId) => {
      navigate(`/pdf/maintain/-${clientId}T${templateId}`);
    };

    const generateColorFromKey = (key) => {
      let hash = 0;
      for (let i = 0; i < key.length; i++) {
          hash += key.charCodeAt(i);
      }

      const baseHue = (hash * 37) % 360; // Multiply by a prime number for better distribution
      const saturation = 120; // Higher saturation for more vibrant colors
      const lightness = 30; // Lower lightness for darker colors

      return `hsl(${baseHue}, ${saturation}%, ${lightness}%)`;
  };
  
    return (
      <Dialog
        open={isWindowOpen}
        onClose={handleOnClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
        PaperProps={{
            sx: {
            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '30vw' },
            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '50vh' }
            }
        }}
        >
        <DialogTitle id="alert-dialog-title">
            <Typography variant="lionerBold" component="span">
            Select Template
            </Typography>
        </DialogTitle>
        <DialogContent>
            <DialogContentText id="alert-dialog-description">
                {Object.keys(templateList).length === 0 ? (
                    <Typography variant="lionerSize" component="span">
                        No available template, please add!
                    </Typography>
                ) : (
                    <>
                    {currentView === 'prefixSelection' ? (
                        // Step 1: Show the prefix selection buttons
                        Object.keys(templateList).map(prefix => (
                            <div key={prefix} style={{ margin: '10px' }}>
                                <Button
                                    variant="contained"
                                    sx={{ backgroundColor: generateColorFromKey(prefix), color: 'white', mr: 1 }}
                                    onClick={() => {
                                        setSelectedPrefix(prefix);
                                        setCurrentView('templateList');
                                    }}
                                >
                                    {prefix}
                                </Button>
                            </div>
                        ))
                    ) : (
                        // Step 2: Show the templates for the selected prefix
                        <>
                            <Button onClick={() => setCurrentView('prefixSelection')}>
                                <Typography variant="lionerSize" component="span">
                                    &lt; Back to Prefixes
                                </Typography>
                            </Button>
                            <Typography variant="lionerBold" sx={{ml: 2}}>
                                Select a {selectedPrefix} Template
                            </Typography>
                            {templateList[selectedPrefix].map(record => (
                                <div key={record.id} style={{ margin: '10px' }}>
                                    <Button
                                        variant="contained"
                                        sx={{ backgroundColor: generateColorFromKey(record.name.split(' ')[0]), color: 'white', mr: 1 }}
                                        onClick={() => createNewForm(record.id)}
                                    >
                                        {record.name}
                                    </Button>
                                </div>
                            ))}
                        </>
                    )}
                    </>
                )}
            </DialogContentText>
        </DialogContent>
        <DialogActions>
            <Button onClick={onNormalClose}>
            <Typography variant="lionerSize" component="span">
                Cancel
            </Typography>
            </Button>
            
        </DialogActions>
        </Dialog>

    );
}