import * as React from 'react';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import Footer from "../Footer";
import Header from "../Header";
import {Button, Checkbox, FormControlLabel, FormGroup, FormLabel, Grid, Paper, Radio, RadioGroup, TextField } from '@mui/material';
import PersonalSection from './PersonalSection1';
import { styled } from '@mui/material/styles';
import ArrowForwardIosSharpIcon from '@mui/icons-material/ArrowForwardIosSharp';
import MuiAccordion, { AccordionProps } from '@mui/material/Accordion';
import MuiAccordionSummary, {
  AccordionSummaryProps,
} from '@mui/material/AccordionSummary';
import MuiAccordionDetails from '@mui/material/AccordionDetails';
import MedicalHistory from './MedicalHistorySection3';
import FamilyFormSection from './FamilyFormSection2';
import PainAnalysisSection4 from './PainAnalysisSection4';
import PastTreatment5 from './PastTreatment5';
import SystemReviewSection6 from './SyestemReviewSection6';
import RecreationalHobbiesSection7 from './RecreationalHobbiesSection7';
import OtherDetails8 from './OtherDetails8';
import PatientImageMarker from '../ImageMarker/PatientImageMarker';

  const Accordion = styled((props: AccordionProps) => (
    <MuiAccordion disableGutters elevation={0} square {...props} />
  ))(({ theme }) => ({
    border: `1px solid ${theme.palette.divider}`,
    '&:not(:last-child)': {
      borderBottom: 0,
    },
    '&:before': {
      display: 'none',
    },
  }));
  
  const AccordionSummary = styled((props: AccordionSummaryProps) => (
    <MuiAccordionSummary
      expandIcon={<ArrowForwardIosSharpIcon sx={{ fontSize: '0.9rem' }} />}
      {...props}
    />
  ))(({ theme }) => ({
    backgroundColor:
      theme.palette.mode === 'dark'
        ? 'rgba(255, 255, 255, .05)'
        : 'rgba(0, 0, 0, .03)',
    flexDirection: 'row-reverse',
    '& .MuiAccordionSummary-expandIconWrapper.Mui-expanded': {
      transform: 'rotate(90deg)',
    },
    '& .MuiAccordionSummary-content': {
      marginLeft: theme.spacing(1),
    },
  }));
  
  const AccordionDetails = styled(MuiAccordionDetails)(({ theme }) => ({
    padding: theme.spacing(2),
    borderTop: '1px solid rgba(0, 0, 0, .125)',
  }));

type Props={
  type:any;
}

export default function PatientForm({type}:Props){
    const [expanded, setExpanded] = React.useState<string | false>('panel1');
    const [isChecked, setIsChecked] = React.useState(false);
    const [signature,setSignature]=React.useState('');
    const [section1Data, setSection1Data] = React.useState<any>({});
    const [section2Data, setSection2Data] = React.useState<any>({});
    const [section3Data, setSection3Data] = React.useState<any>({});
    const [section4Data, setSection4Data] = React.useState<any>({});
    const [section5Data, setSection5Data] = React.useState<any>({});
    const [section6Data, setSection6Data] = React.useState<any>({});
    const [section7Data, setSection7Data] = React.useState<any>({});
    const [section8Data, setSection8Data] = React.useState<any>({});
    const [allPatientData, setAllPatientData] = React.useState<any>([]);

    const handleFormSection1Data = (
      fullName?: string|undefined,
      homePhone?: string|undefined,
      cellPhone?: string|undefined,
      email?: string|undefined,
      age?: number|undefined|string,
      dateOfBirth?: string|undefined,
      socialSecurityNumber?: string|undefined,
      mailingAddress?: string|undefined,
      city?: string|undefined,
      state?: string|undefined,
      zipCode?: string|undefined,
      gender?: string|undefined,
    ) =>{
      setSection1Data({
        fullName,
        homePhone,
        cellPhone,
        email,
        age,
        dateOfBirth,
        socialSecurityNumber,
        mailingAddress,
        city,
        state,
        zipCode,
        gender,
      })
    }

    const handleFormSection2Data = (
      maritalStatus: string | undefined,
      numberOfChildren: string | undefined,
      occupation: string | undefined,
      hoursPerWeek: number | string | undefined,
      employer: string | undefined,
      businessPhone: string | undefined,
      spouseName: string | undefined,
      spouseEmployer: string | undefined,
      spouseBusinessPhone: string | undefined,
      emergencyContact: string | undefined,
      relationship: string | undefined,
      spousePhone: string | undefined,
    ) =>{
      setSection2Data({
        maritalStatus,
        numberOfChildren,
        occupation,
        hoursPerWeek,
        employer,
        businessPhone,
        spouseName,
        spouseEmployer,
        spouseBusinessPhone,
        emergencyContact,
        relationship,
        spousePhone,
      })
    }

    const handleFormSection3Data = (
      physicianname: string |undefined,
      physiciancity: string |undefined,
      physicianstate: string |undefined,
      physicianphone: string |undefined,
      chiropractorName: string |undefined,
      chiropractorState: string |undefined,
      xray: string|undefined,
      haveChiropractor: string|undefined,
      reference: string|undefined,
      visitDetails: string |undefined,
      cellPhoneProvider: string |undefined,
    ) =>{
      setSection3Data({
        physicianname,
        physiciancity,
        physicianstate,
        physicianphone,
        chiropractorName,
        chiropractorState,
        xray,
        haveChiropractor,
        reference,
        visitDetails,
        cellPhoneProvider,
      })
    }

    const handleFormSection4Data = (
        chiefComplaint:string|undefined,
        painWorse: any,
        painBetter: any,
        painQuality: any,
        painWorstTime: any,
        currentComplaintIssues: any,
        painDuration: string|undefined,
        currentTreatment: string|undefined,
        treatmentGoal: string|undefined,
        selfTreatment:string|undefined,
    ) =>{
      setSection4Data({
        chiefComplaint,
        painWorse,
        painBetter,
        painQuality,
        painWorstTime,
        currentComplaintIssues, 
        painDuration,
        currentTreatment,
        treatmentGoal,
        selfTreatment,
      })
    }

    const handleFormSection5Data = (
      generalHealth: string|undefined,
      presentProblemBefore: string|undefined,
      ifYespresentProblemBefore:string|undefined,
      ifYestreatmentProvided: string|undefined,
      ifYesOutcome: string|undefined,
      strokeBloodclotting: string|undefined,
      ifYesstrokeBloodclotting: string|undefined,
      dizzinessFetigue: string|undefined,
      ifyesdizzinessFetigue: string|undefined,
      antiColligent: string|undefined,
      injuriesHospitalization: string|undefined,
      supplementsOrDrugs: string|undefined,
    ) =>{
      setSection5Data({
        generalHealth,
        presentProblemBefore,
        ifYespresentProblemBefore,
        ifYestreatmentProvided,
        ifYesOutcome,
        strokeBloodclotting,
        ifYesstrokeBloodclotting,
        dizzinessFetigue,
        ifyesdizzinessFetigue,
        antiColligent,
        injuriesHospitalization,
        supplementsOrDrugs,
      })
    }

    const handleFormSection6Data = (
      eyes: string|undefined,
      IntestinesBowls: string|undefined,
      jointsBones:string|undefined,
      allergies: string|undefined,
      earsNoseMouth: string|undefined,
      urinary: string|undefined,
      skin: string|undefined,
      psychological: string|undefined,
      heart: string|undefined,
      muscles: string|undefined,
      internalOrgans: string|undefined,
      gynecological: string|undefined,
      lungsBreathing: string|undefined,
      nerves: string|undefined,
      blood: string|undefined,
      prostate: string|undefined,
      explanation:string|undefined,
    ) =>{
      setSection6Data({
        eyes,
        IntestinesBowls,
        jointsBones,
        allergies,
        earsNoseMouth,
        urinary,
        skin,
        psychological,
        heart,
        muscles,
        internalOrgans,
        gynecological,
        lungsBreathing,
        nerves,
        blood,
        prostate,
        explanation,
      })
    }


    const handleFormSection7Data = (
      hobbies: string|undefined,
      educationLevel: string|undefined,
      excercise: string|undefined,
      excerciseExplanation: string|undefined,
      tobacco: string|undefined,
      tobaccoExplanation: string|undefined,
      alcohol: string|undefined,
      alcoholExplanation: string|undefined,
      healthyDiet: string|undefined,
      healthyDietExplanation: string|undefined,
      sleep: string|undefined,
      sleepExplanation: string|undefined,
      workSchool: string|undefined,
      workSchoolExplanation: string|undefined,
      familyLife: string|undefined,
      familyLifeExplanation: string|undefined,
      drugs: string|undefined,
      drugsExplanation:string|undefined,
    ) =>{
      setSection7Data({
        hobbies,
        educationLevel,
        excercise,
        excerciseExplanation,
        tobacco,
        tobaccoExplanation,
        alcohol,
        alcoholExplanation,
        healthyDiet,
        healthyDietExplanation,
        sleep,
        sleepExplanation,
        workSchool,
        workSchoolExplanation,
        familyLife,
        familyLifeExplanation,
        drugs,
        drugsExplanation,
      })
    }

    const handleFormSection8Data = (
      familyHistory: string|undefined,
      sleep: string|undefined,
      pillow: string|undefined,
      orthotics: string|undefined,
      brestExam: any,
      pregnancy: string|undefined,
      menstralCycle: any,
    ) =>{
      setSection8Data({
        familyHistory,
        sleep,
        pillow,
        orthotics,
        brestExam,
        pregnancy,
        menstralCycle,
      })
    }    
    
    const handleSubmit = () => {
      const newPatientData = {
        personalInformation: section1Data,
        familyInformation: section2Data,
        medicalHistory: section3Data,
        injuryDetails: section4Data,
        pastTreatment: section5Data,
        systemReviewQuestions: section6Data,
        recreationalActivities: section7Data,
        otherDetails: section8Data,
      };
    
      // Create a copy of the existing data array and push the new patient data
      const updatedAllPatientData = [...allPatientData, newPatientData];
    
      // Update the state with the new array
      setAllPatientData(updatedAllPatientData);

      localStorage.setItem('patientData', JSON.stringify(newPatientData));
      TextFile();
  };
  
  const TextFile = () => {
    const element = document.createElement("a");
    //@ts-ignore
    const textFile = new Blob([localStorage.getItem('patientData')], {type: 'text/json'});
    element.href = URL.createObjectURL(textFile);
    element.download = "patientData.json";
    document.body.appendChild(element); 
    element.click();
  }
    

      const handleExpandChange =
        (panel: string) => (event: React.SyntheticEvent, newExpanded: boolean) => {
        setExpanded(newExpanded ? panel : false);
        };
 
      const handleCheckboxChange = (event:any) => {
        setIsChecked(event.target.checked);
      };

      //@ts-ignore
      const patientData = localStorage.getItem('patientData') ? JSON.parse(localStorage.getItem('patientData')) : [];

    return(
        <>
            <Paper elevation={0} className='app-screen-constants'>
                <Header/>
                    <Paper  elevation={0} sx={{margin:4, minHeight:550}} >
                    {/* <form onSubmit={handleSubmit}> */}
                        <Typography sx={{fontSize:20}}  gutterBottom>
                            Confidential Patient Information
                        </Typography>
                        <Grid>
                        <Accordion expanded={expanded === 'panel1'} onChange={handleExpandChange('panel1')}>
                            
                            <AccordionSummary
                                expandIcon={<ExpandMoreIcon />}
                                aria-controls="panel1a-content"
                                id="panel1a-header"
                                >
                                <Typography sx={{fontSize:18}}>Patient's Personal Information</Typography>
                            </AccordionSummary>
                           
                            <AccordionDetails>
                                <PersonalSection 
                                  handleFormSection1Data={handleFormSection1Data}
                                  patientDataDiplay={patientData.personalInformation}
                                  type={type}
                                  
                                  />
                            </AccordionDetails>
                           
                        </Accordion>

                        <Accordion expanded={expanded === 'panel2'} onChange={handleExpandChange('panel2')}>
                            <AccordionSummary aria-controls="panel2d-content" id="panel2d-header">
                                <Typography sx={{fontSize:18}}>Patient's Family Information</Typography>
                            </AccordionSummary>

                            <AccordionDetails>
                                <FamilyFormSection 
                                handleFormSection2Data={handleFormSection2Data}
                                patientDataDiplay={patientData.familyInformation}
                                type={type}
                                  />
                            </AccordionDetails>
                        </Accordion>

                        <Accordion expanded={expanded === 'panel3'} onChange={handleExpandChange('panel3')}>
                            <AccordionSummary aria-controls="panel3d-content" id="panel3d-header">
                                <Typography sx={{fontSize:18}}>Patient's Medical History Information</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <MedicalHistory 
                                handleFormSection3Data={handleFormSection3Data}
                                patientDataDiplay={patientData.medicalHistory}
                                type={type}
                                />
                            </AccordionDetails>
                        </Accordion>
                
                        <Accordion expanded={expanded === 'panel9'} onChange={handleExpandChange('panel9')}>
                            <AccordionSummary aria-controls="panel9d-content" id="panel9d-header">
                                <Typography sx={{fontSize:18}}>Patient's Injury Image</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <PatientImageMarker />
                            </AccordionDetails>
                        </Accordion>


                        <Accordion expanded={expanded === 'panel4'} onChange={handleExpandChange('panel4')}>
                            <AccordionSummary aria-controls="panel4d-content" id="panel4d-header">
                                <Typography sx={{fontSize:18}}>Patient's Injury Details</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <PainAnalysisSection4
                                 handleFormSection4Data={handleFormSection4Data}
                                 patientDataDiplay={patientData.injuryDetails}
                                  type={type}
                                  />
                            </AccordionDetails>
                        </Accordion>

                        <Accordion expanded={expanded === 'panel5'} onChange={handleExpandChange('panel5')}>
                            <AccordionSummary aria-controls="panel5d-content" id="panel5d-header">
                                <Typography sx={{fontSize:18}}>Patient's Past Treatment Details</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <PastTreatment5 
                                handleFormSection5Data={handleFormSection5Data}
                                patientDataDiplay={patientData.pastTreatment}
                                type={type}/>
                            </AccordionDetails>
                        </Accordion>

                        <Accordion expanded={expanded === 'panel6'} onChange={handleExpandChange('panel6')}>
                            <AccordionSummary aria-controls="panel6d-content" id="panel6d-header">
                                <Typography sx={{fontSize:18}}>System Review Questions</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <SystemReviewSection6 
                                handleFormSection6Data={handleFormSection6Data}
                                patientDataDiplay={patientData.systemReviewQuestions}
                                type={type}
                                />
                            </AccordionDetails>
                        </Accordion>

                        <Accordion expanded={expanded === 'panel7'} onChange={handleExpandChange('panel7')}>
                            <AccordionSummary aria-controls="panel7d-content" id="panel7d-header">
                                <Typography sx={{fontSize:18}}>Recreational Activities/Hobbies Details</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <RecreationalHobbiesSection7 
                                handleFormSection7Data={handleFormSection7Data}
                                patientDataDiplay={patientData.systemReviewQuestions}
                                type={type}/>
                            </AccordionDetails>
                        </Accordion>

                        <Accordion expanded={expanded === 'panel8'} onChange={handleExpandChange('panel8')}>
                            <AccordionSummary aria-controls="panel8d-content" id="panel8d-header">
                                <Typography sx={{fontSize:18}}>Other Details</Typography>
                            </AccordionSummary>
                            
                            <AccordionDetails>
                                <OtherDetails8 handleFormSection8Data={handleFormSection8Data}/>
                            </AccordionDetails>
                        </Accordion>

                        <Grid container>

                        <Grid item xs={12} className='collapsable-form-style-multiline'>
                          <FormGroup sx={{ marginTop: 3 }}>
                            <FormControlLabel
                              required
                              control={<Checkbox checked={isChecked} onChange={handleCheckboxChange} />}
                              label="I hereby state that all the information I have provided is complete and truthful and that I have fully disclosed my health history."
                            />
                          </FormGroup>
                        </Grid>

                        <Grid item xs={6} className='collapsable-form-style'>
                              <TextField 
                              
                              variant="outlined"
                              label="SIGNATURE" 
                              name='treatmentGoal'
                              placeholder='Please type your name'
                              onChange={(event) => {
                                setSignature(event.target.value)
                              }}
                              />
                        </Grid>
                        </Grid>                
                        <Grid>
                          <Button
                            // type="submit"
                            variant="contained"
                            color="primary"
                            sx={{ margin: 5, left: '40%', width: '200px' }}
                            disabled={isChecked==false || signature==''}
                            onClick={handleSubmit}
                          >
                            Submit
                          </Button>
                        </Grid>
                        </Grid>
                        {/* </form> */}
                       
                    </Paper>
                <Footer/>
             </Paper>
        </>
    )
}