import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import Accordion from '@mui/material/Accordion';
import AccordionDetails from '@mui/material/AccordionDetails';
import AccordionSummary from '@mui/material/AccordionSummary';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import FormControl from '@mui/material/FormControl';
import Grid from '@mui/material/Grid';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Paper from '@mui/material/Paper';
import Select from '@mui/material/Select';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import * as React from 'react';

// Days of week for clinic timings
const daysOfWeek = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];

// Integration software options
const integrationOptions = ['BP Software', 'Medical Director', 'Other'];

export default function ClinicSetupAccordion() {
  // State for expanded accordion panel
  const [expanded, setExpanded] = React.useState('generalInfo');

  const handleAccordionChange = (panel) => (event, isExpanded) => {
    setExpanded(isExpanded ? panel : false);
  };

  // Form state
  const [formData, setFormData] = React.useState({
    // General Information
    clinicPhone: '',
    clinicAddress: '',
    otherInfo: '',

    // Clinic Timings
    regularTimings: daysOfWeek.reduce(
      (acc, day) => ({
        ...acc,
        [day]: { open: '', close: '' },
      }),
      {}
    ),
    emergencyTimings: daysOfWeek.reduce(
      (acc, day) => ({
        ...acc,
        [day]: { open: '', close: '' },
      }),
      {}
    ),

    // Greetings Setup
    clinicGreetings: '',

    // Integration Settings
    integrationSoftware: '',
    practiceId: '',
    practiceName: '',
  });

  // Handle simple input changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  // Handle timing changes
  const handleTimingChange = (timingType, day, timeType, value) => {
    setFormData((prev) => ({
      ...prev,
      [timingType]: {
        ...prev[timingType],
        [day]: {
          ...prev[timingType][day],
          [timeType]: value,
        },
      },
    }));
  };

  // Handle form submission
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
    // Here you would typically send the data to your backend
    alert('Clinic setup completed successfully!');
  };

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ width: '100%' }}>
      <Paper elevation={0} sx={{ p: 2 }}>
        <Typography
          variant="h4"
          component="h1"
          sx={{ color: '#1976d2', fontWeight: 'bold', mb: 3 }}
        >
          Clinic Setup
        </Typography>

        {/* General Information Accordion */}
        <Accordion
          expanded={expanded === 'generalInfo'}
          onChange={handleAccordionChange('generalInfo')}
          sx={{ mb: 2 }}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="generalInfo-content"
            id="generalInfo-header"
            sx={{ backgroundColor: '#f5f5f5' }}
          >
            <Typography variant="h6" sx={{ fontWeight: 'medium' }}>
              Scenario
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  required
                  fullWidth
                  label="Clinic Phone Number"
                  name="clinicPhone"
                  value={formData.clinicPhone}
                  onChange={handleChange}
                  helperText="Unique single number for your clinic"
                  variant="outlined"
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  required
                  fullWidth
                  label="Clinic Address"
                  name="clinicAddress"
                  value={formData.clinicAddress}
                  onChange={handleChange}
                  multiline
                  rows={3}
                  variant="outlined"
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Other Information"
                  name="otherInfo"
                  value={formData.otherInfo}
                  onChange={handleChange}
                  multiline
                  rows={2}
                  variant="outlined"
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* Clinic Timings Accordion */}
        <Accordion
          expanded={expanded === 'clinicTimings'}
          onChange={handleAccordionChange('clinicTimings')}
          sx={{ mb: 2 }}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="clinicTimings-content"
            id="clinicTimings-header"
            sx={{ backgroundColor: '#f5f5f5' }}
          >
            <Typography variant="h6" sx={{ fontWeight: 'medium' }}>
              Clinic Timings
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Box>
              <Typography
                variant="subtitle1"
                gutterBottom
                sx={{ fontWeight: 'medium', mt: 1 }}
              >
                Regular Timings (Daywise)
              </Typography>
              <Grid container spacing={2}>
                {daysOfWeek.map((day) => (
                  <React.Fragment key={`regular-${day}`}>
                    <Grid item xs={12} sm={4}>
                      <Typography variant="body1">{day}</Typography>
                    </Grid>
                    <Grid item xs={6} sm={4}>
                      <TextField
                        fullWidth
                        label="Open"
                        type="time"
                        InputLabelProps={{ shrink: true }}
                        value={formData.regularTimings[day].open}
                        onChange={(e) =>
                          handleTimingChange(
                            'regularTimings',
                            day,
                            'open',
                            e.target.value
                          )
                        }
                        variant="outlined"
                        size="small"
                      />
                    </Grid>
                    <Grid item xs={6} sm={4}>
                      <TextField
                        fullWidth
                        label="Close"
                        type="time"
                        InputLabelProps={{ shrink: true }}
                        value={formData.regularTimings[day].close}
                        onChange={(e) =>
                          handleTimingChange(
                            'regularTimings',
                            day,
                            'close',
                            e.target.value
                          )
                        }
                        variant="outlined"
                        size="small"
                      />
                    </Grid>
                  </React.Fragment>
                ))}
              </Grid>

              <Typography
                variant="subtitle1"
                gutterBottom
                sx={{ fontWeight: 'medium', mt: 4 }}
              >
                Emergency Timings (Daywise)
              </Typography>
              <Grid container spacing={2}>
                {daysOfWeek.map((day) => (
                  <React.Fragment key={`emergency-${day}`}>
                    <Grid item xs={12} sm={4}>
                      <Typography variant="body1">{day}</Typography>
                    </Grid>
                    <Grid item xs={6} sm={4}>
                      <TextField
                        fullWidth
                        label="Open"
                        type="time"
                        InputLabelProps={{ shrink: true }}
                        value={formData.emergencyTimings[day].open}
                        onChange={(e) =>
                          handleTimingChange(
                            'emergencyTimings',
                            day,
                            'open',
                            e.target.value
                          )
                        }
                        variant="outlined"
                        size="small"
                      />
                    </Grid>
                    <Grid item xs={6} sm={4}>
                      <TextField
                        fullWidth
                        label="Close"
                        type="time"
                        InputLabelProps={{ shrink: true }}
                        value={formData.emergencyTimings[day].close}
                        onChange={(e) =>
                          handleTimingChange(
                            'emergencyTimings',
                            day,
                            'close',
                            e.target.value
                          )
                        }
                        variant="outlined"
                        size="small"
                      />
                    </Grid>
                  </React.Fragment>
                ))}
              </Grid>
            </Box>
          </AccordionDetails>
        </Accordion>

        {/* Greetings Setup Accordion */}
        <Accordion
          expanded={expanded === 'greetingsSetup'}
          onChange={handleAccordionChange('greetingsSetup')}
          sx={{ mb: 2 }}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="greetingsSetup-content"
            id="greetingsSetup-header"
            sx={{ backgroundColor: '#f5f5f5' }}
          >
            <Typography variant="h6" sx={{ fontWeight: 'medium' }}>
              Greetings Setup
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <TextField
              fullWidth
              label="Clinic Greetings"
              name="clinicGreetings"
              value={formData.clinicGreetings}
              onChange={handleChange}
              multiline
              rows={3}
              variant="outlined"
              helperText={`${formData.clinicGreetings.length}/200 characters`}
              inputProps={{ maxLength: 200 }}
            />
          </AccordionDetails>
        </Accordion>

        {/* Integration Settings Accordion */}
        <Accordion
          expanded={expanded === 'integrationSettings'}
          onChange={handleAccordionChange('integrationSettings')}
          sx={{ mb: 2 }}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="integrationSettings-content"
            id="integrationSettings-header"
            sx={{ backgroundColor: '#f5f5f5' }}
          >
            <Typography variant="h6" sx={{ fontWeight: 'medium' }}>
              Integration Settings
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <FormControl fullWidth variant="outlined">
                  <InputLabel id="integration-software-label">
                    Integrate with
                  </InputLabel>
                  <Select
                    labelId="integration-software-label"
                    label="Integrate with"
                    name="integrationSoftware"
                    value={formData.integrationSoftware}
                    onChange={handleChange}
                  >
                    <MenuItem value="">
                      <em>None</em>
                    </MenuItem>
                    {integrationOptions.map((option) => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Practice ID"
                  name="practiceId"
                  value={formData.practiceId}
                  onChange={handleChange}
                  variant="outlined"
                  disabled={!formData.integrationSoftware}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Practice Name"
                  name="practiceName"
                  value={formData.practiceName}
                  onChange={handleChange}
                  variant="outlined"
                  disabled={!formData.integrationSoftware}
                />
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>

        {/* Form Actions */}
        <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 3 }}>
          <Button
            variant="outlined"
            sx={{ mr: 2 }}
            onClick={() => {
              if (window.confirm('Are you sure you want to reset the form?')) {
                setFormData({
                  clinicPhone: '',
                  clinicAddress: '',
                  otherInfo: '',
                  regularTimings: daysOfWeek.reduce(
                    (acc, day) => ({
                      ...acc,
                      [day]: { open: '', close: '' },
                    }),
                    {}
                  ),
                  emergencyTimings: daysOfWeek.reduce(
                    (acc, day) => ({
                      ...acc,
                      [day]: { open: '', close: '' },
                    }),
                    {}
                  ),
                  clinicGreetings: '',
                  integrationSoftware: '',
                  practiceId: '',
                  practiceName: '',
                });
              }
            }}
          >
            Reset
          </Button>
          <Button type="submit" variant="contained" color="primary">
            Save Clinic Setup
          </Button>
        </Box>
      </Paper>
    </Box>
  );
}
