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

'use client';

import React, { useState, useContext } from 'react';
import { useRouter } from 'next/navigation';
import {
  Box,
  Button,
  Stack,
  TextField,
  Typography,
} from '@mui/material';
import { UserContext } from '@/contexts/user-context';

export default function AddTagPage() {
  const router = useRouter();
  const { user: loggedInUser } = useContext(UserContext) ?? {};

 

  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleAddTag = async () => {
    if (!name ) {
      setError('Please fill in all fields.');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const res = await fetch('/admin/api/typesvisit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name,
          manager_id: loggedInUser?.id,
          company_id: loggedInUser?.companies?.find((c: any) => c.active)?.id || '',
        }),
      });

      if (!res.ok) {
        throw new Error('Failed to add tag');
      }

      router.push('/dashboard/visittypes');
    } catch (err: any) {
      setError(err.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ p: 4 }}>
      <Typography variant="h4" gutterBottom>Add New Visit</Typography>

      <Stack spacing={3} sx={{ maxWidth: 400 }}>
        <TextField
          label="Visit Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          fullWidth
        />

        

        {error && <Typography color="error">{error}</Typography>}

        <Button
          variant="contained"
          onClick={handleAddTag}
          disabled={loading}
        >
          {loading ? 'Adding...' : 'Add Visit Type'}
        </Button>
      </Stack>
    </Box>
  );
}
