/* eslint-disable -- temporary disable for development/testing purposes */

'use client';
import * as React from 'react';

import {
  Box,
  Button,
  Grid,
  MenuItem,
  TextField,
  Typography,
  Avatar,
  CircularProgress,
  IconButton, // Import IconButton
  InputAdornment, // Import InputAdornment
} from '@mui/material';
import { useEffect, useState, useContext } from 'react';
import { UserContext } from '@/contexts/user-context';
import { useRouter } from 'next/navigation';
import { Snackbar, Alert } from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material'; // Import eye icons

interface FormData {
  f_name: string | null;
  l_name: string | null;
  email: string | null;
  mobile_number: string | null;
  password: string | null;
  gender: string | null;
  dob: string | null;
  address: string | null;
  age: string | null;
  referral_source: string | null;
  z_code: string | null;
  company_id: string | null;
  lat: string | null;
  lng: string | null;
  status: 'active' | 'inactive' | null; // Added status field
}

const AddPatient = () => {
  const [formData, setFormData] = useState<FormData>({
    f_name: '',
    l_name: '',
    email: '',
    mobile_number: '',
    password: '',
    gender: '',
    dob: '',
    address: '',
    age: '',
    referral_source: '',
    z_code: '',
    company_id: '',
    lat: '',
    lng: '',
    status: 'active', // Default status
  });

  const [profile, setProfile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  const [showPassword, setShowPassword] = useState(false); // State for password visibility
  const router = useRouter();
  useEffect(() => {
    if (!loggedInUser) return;

    if (loggedInUser.role === 'manager' && loggedInUser.companies?.length > 0) {
      const activeCompany = loggedInUser.companies.find((company) => company.active);
      if (activeCompany) {
        setFormData((prev) => ({
          ...prev,
          company_id: activeCompany.id?.toString() ?? null,
        }));
      }
    }
  }, [loggedInUser]);

  useEffect(() => {
    if (!window.google) return;

    const input = document.getElementById('address-autocomplete') as HTMLInputElement;
    if (!input) return;

    const autocomplete = new window.google.maps.places.Autocomplete(input, {
      types: ['geocode'],
    });

    const placesService = new window.google.maps.places.PlacesService(input);

    autocomplete.addListener('place_changed', () => {
      const place = autocomplete.getPlace();

      const geometry = place?.geometry;
      const location = geometry?.location;

      if (location) {
        setFormData((prev) => ({
          ...prev,
          address: place.formatted_address || prev.address,
          lat: location.lat().toString(),
          lng: location.lng().toString(),
        }));
      } else {
        console.log("No valid geometry and location found for the selected place.");
        setFormData(prev => ({ ...prev, lat: '', lng: '' }));
      }
    });

    return () => {
      if (autocomplete) {
        window.google.maps.event.clearInstanceListeners(autocomplete);
      }
    };
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    if (name === 'dob') {
      calculateAge(value);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setProfile(e.target.files[0]);
    }
  };

  const handleSubmit = async () => {
    console.log('Form Data before validation and submission:', formData);

    if (!formData.f_name?.trim()) {
      console.error('Validation Error: First Name is required.');
      return;
    }
    if (!formData.l_name?.trim()) {
      console.error('Validation Error: Last Name is required.');
      return;
    }
    if (!formData.email?.trim()) {
      console.error('Validation Error: Email is required.');
      return;
    } else if (formData.email && !/\S+@\S+\.\S+/.test(formData.email)) {
      console.error('Validation Error: Invalid email format.');
      return;
    }
    if (!formData.mobile_number?.trim()) {
      console.error('Validation Error: Mobile Number is required.');
      return;
    }

    const data = new FormData();
    const fullName = `${formData.f_name} ${formData.l_name}`.trim();
    data.append('name', fullName);

    const dataToSend: typeof formData = { ...formData };

    for (const key in dataToSend) {
      if (dataToSend[key as keyof typeof formData] === '') {
        dataToSend[key as keyof typeof formData] = null;
      }
    }

    for (const key in dataToSend) {
      if (key !== 'f_name' && key !== 'l_name') {
        data.append(
          key,
          dataToSend[key as keyof typeof formData] === null
            ? ''
            : dataToSend[key as keyof typeof formData]!
        );
      }
    }

    if (profile) {
      data.append('profile', profile);
    }

    setLoading(true);

    try {
      const response = await fetch('/admin/api/customers/add', {
        method: 'POST',
        body: data,
      });

      let responseData;
      try {
        responseData = await response.json();
      } catch (err) {
        console.error('Failed to parse JSON:', err);
      }

      if (!response.ok) {
        console.error('Server Error:', responseData?.error || 'Unknown error');
      } else {
        console.log('Patient added:', responseData.message);
        setFormData({
          f_name: null,
          l_name: null,
          email: null,
          mobile_number: null,
          password: null,
          gender: null,
          dob: null,
          address: null,
          age: null,
          referral_source: null,
          z_code: null,
          company_id:
            loggedInUser?.role === 'manager'
              ? loggedInUser.companies?.find((c) => c.active)?.id?.toString() ?? null
              : null,
          lat: null,
          lng: null,
          status:null
        });
        setProfile(null);
        setSnackbarMessage('Patient added successfully');
        // Send welcome email
await sendWelcomeEmail(fullName, formData.email || '', formData.password || '');

        setSnackbarSeverity('success');
        setSnackbarOpen(true);
  
        // Redirect to /customers after a delay
        setTimeout(() => {
          router.push('/dashboard/customers');
        }, 2000);
      }
    } catch (err) {
      console.error('Unexpected error:', err);
    } finally {
      setLoading(false);
    }
  };

  const sendWelcomeEmail = async (name: string, email: string, password: string) => {
    if (!loggedInUser?.name) {
      console.error('Manager name not available, cannot send welcome email.');
      return;
    }
  
    const emailData = new FormData();
    emailData.append('name', name);
    emailData.append('receiver_email', email);
    emailData.append('user_type', 'patient');
    emailData.append('password', password);
    emailData.append('manager_name', loggedInUser.name);
    emailData.append('action', 'send_new_user_notification');
  
    try {
      const response = await fetch('https://gohelloprovider.com/api/emailproject/send_email.php', {
        method: 'POST',
        body: emailData,
      });
  
      const data = await response.json();
      console.log('Email API response:', data);
  
      if (data.response === 'success') {
        // setSnackbarMessage('Welcome email sent successfully');
        // setSnackbarSeverity('success');
      } else {
        // setSnackbarMessage('Failed to send welcome email');
        // setSnackbarSeverity('error');
      }
      // setSnackbarOpen(true);
    } catch (error) {
      console.error('Error sending welcome email:', error);
      // setSnackbarMessage('Error sending welcome email');
      // setSnackbarSeverity('error');
      // setSnackbarOpen(true);
    }
  };

  
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const handleMouseDownPassword = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
  };

  const calculateAge = (dob: string | null) => {
    if (dob) {
      const birthDate = new Date(dob);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      setFormData((prev) => ({ ...prev, age: age.toString() }));
    } else {
      setFormData((prev) => ({ ...prev, age: '' }));
    }
  };

  return (
    <>
    <Box sx={{ maxWidth: 600, mx: 'auto', mt: 4, p: 3, bgcolor: '#fff', borderRadius: 2 }}>
      <Typography variant="h5" gutterBottom>
        Add New Patient
      </Typography>

      <Grid container spacing={2}>
        <Grid item xs={12} textAlign="center">
          <Avatar
            alt="Profile"
            src={profile ? URL.createObjectURL(profile) : ''}
            sx={{ width: 100, height: 100, margin: '0 auto', mb: 1 }}
          />
          <Button variant="outlined" component="label">
            {profile ? 'Change Profile' : 'Upload Profile'}
            <input hidden type="file" accept="image/*" onChange={handleFileChange} />
          </Button>
        </Grid>

        <Grid item xs={6}>
          <TextField label="First Name" name="f_name" value={formData.f_name || ''} onChange={handleChange} fullWidth />
        </Grid>

        <Grid item xs={6}>
          <TextField label="Last Name" name="l_name" value={formData.l_name || ''} onChange={handleChange} fullWidth />
        </Grid>

        <Grid item xs={6}>
          <TextField
            label="Email"
            name="email"
            autoComplete="off"
            type="email"
            value={formData.email || ''}
            onChange={handleChange}
            fullWidth
          />
        </Grid>

        <Grid item xs={6}>
          <TextField
            autoComplete="off"
            type="tel"
            label="Mobile Number"
            name="mobile_number"
            value={formData.mobile_number || ''}
            onChange={handleChange}
            fullWidth
          />
        </Grid>

        <Grid item xs={6}>
          <TextField
            autoComplete="new-password"
            label="Password"
            name="password"
            type={showPassword ? 'text' : 'password'} 
            value={formData.password || ''}
            onChange={handleChange}
            fullWidth
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={handleClickShowPassword}
                    onMouseDown={handleMouseDownPassword}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Grid>

        <Grid item xs={6}>
          <TextField label="Age" name="age" type="number" value={formData.age || ''} onChange={handleChange} fullWidth />
        </Grid>

        <Grid item xs={6}>
          <TextField label="Gender" name="gender" select value={formData.gender || ''} onChange={handleChange} fullWidth>
            <MenuItem value="">Select Gender</MenuItem>
            <MenuItem value="male">Male</MenuItem>
            <MenuItem value="female">Female</MenuItem>
            <MenuItem value="other">Other</MenuItem>
          </TextField>
        </Grid>

        <Grid item xs={6}>
          <TextField
            label="Date of Birth"
            name="dob"
            type="date"
            value={formData.dob || ''}
            onChange={handleChange}
            InputLabelProps={{ shrink: true }}
            fullWidth
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            id="address-autocomplete"
            label="Address"
            name="address"
            value={formData.address || ''}
            onChange={handleChange}
            fullWidth
            multiline
            rows={2}
          />
        </Grid>

        <Grid item xs={6}>
          <TextField
            label="Referral Source"
            name="referral_source"
            value={formData.referral_source || ''}
            onChange={handleChange}
            fullWidth
          />
        </Grid>

        <Grid item xs={6}>
          <TextField
            label="Zip Code"
            name="z_code"
            value={formData.z_code || ''}
            onChange={handleChange}
            fullWidth
          />
        </Grid>

          {/* New Status Field */}
          <Grid item xs={6}>
            <TextField
              label="Status"
              name="status"
              select
              value={formData.status || 'active'}
              onChange={handleChange}
              fullWidth
            >
              <MenuItem value="active">Active</MenuItem>
              <MenuItem value="inactive">Inactive</MenuItem>
            </TextField>
          </Grid>
        <input type="hidden" name="lat" value={formData.lat || ''} />
        <input type="hidden" name="lng" value={formData.lng || ''} />

        <Grid item xs={12}>
          <Button variant="contained" onClick={handleSubmit} disabled={loading} fullWidth>
            {loading ? <CircularProgress size={22} /> : 'Add Patient'}
          </Button>
        </Grid>
      </Grid>
    </Box>
    <Snackbar
    open={snackbarOpen}
    autoHideDuration={4000}
    onClose={() => setSnackbarOpen(false)}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
  >
    <Alert
      onClose={() => setSnackbarOpen(false)}
      severity={snackbarSeverity}
      variant="filled"
      sx={{ width: '100%' }}
    >
      {snackbarMessage}
    </Alert>
  </Snackbar>
  </>
  );
};

export default AddPatient;
