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

'use client';
import React, { useEffect, useState, useContext } from 'react';
import { useParams } from 'next/navigation';
import {
  Box,
  Typography,
  TextField,
  Button,
  CircularProgress,
  Alert,
} from '@mui/material';
import { UserContext } from '@/contexts/user-context';
import { useRouter } from 'next/navigation';

export default function MedicalChartPage() {
    const router = useRouter();

  const { id: userId } = useParams(); // dynamic route param
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const companyId = loggedInUser?.companies?.find((c: any) => c.active)?.id;
  const managerId = loggedInUser?.id;

  const [form, setForm] = useState({
    medical_history: '',
    diagnosis: '',
    immunizations: '',
    medications: '',
    precautions: '',
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [showBanner, setShowBanner] = useState(false);


  useEffect(() => {
    if (!userId || !companyId) return;

    const fetchData = async () => {
      try {
        const res = await fetch(`/admin/api/medical-chart?userId=${userId}&companyId=${companyId}`);

        const data = await res.json();
        if (data.chart) {
          setForm(data.chart);
        }
      } catch (err) {
        setError('Failed to load chart');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [userId, companyId]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleSubmit = async () => {
    try {
      const res = await fetch('/admin/api/medical-chart', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: userId,
          manager_id: managerId,
          company_id: companyId,
          ...form,
        }),
      });

      const result = await res.json();
      if (!result.success) throw new Error(result.error);
      setSuccess(true);
      setShowBanner(true); // show the banner

      setTimeout(() => {
        setShowBanner(false);
      router.push('/dashboard/customers');

      }, 2000);
    } catch (err) {
      setError('Failed to save');
    }
  };

  if (!userId) return <Alert severity="error">No user selected.</Alert>;
//   if (loading) return <CircularProgress />;

  return (
    <Box sx={{ p: 4 }}>
        {showBanner && (
  <Alert
    severity="success"
    onClose={() => setShowBanner(false)}
    sx={{
      mb: 2,
      borderRadius: 2,
      boxShadow: 3,
      fontWeight: 'bold',
      fontSize: '1rem',
    }}
  >
    Medical chart for this patient has been updated successfully.
  </Alert>
)}
      <Typography variant="h5" gutterBottom>Medical Chart</Typography>

      {error && <Alert severity="error">{error}</Alert>}
      {/* {success && <Alert severity="success">Saved successfully</Alert>} */}
      {loading ? (
  <CircularProgress />
) : (
  <>
    {['medical_history', 'diagnosis', 'immunizations', 'medications', 'precautions'].map((field) => (
      <TextField
        key={field}
        name={field}
        label={field.replace('_', ' ')}
        value={form[field as keyof typeof form]}
        onChange={handleChange}
        multiline
        rows={3}
        fullWidth
        margin="normal"
      />
    ))}
    <Button variant="contained" onClick={handleSubmit}>Save</Button>
  </>
)}




    </Box>
  );
}
