"use client";

import React, { useEffect, useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import {
  Box,
  TextField,
  Button,
  MenuItem,
  Typography,
  Snackbar,
  Alert,
} from "@mui/material";
import axios from "axios";

interface UserFormData {
  role: string;
  agency: string;
  user: string;
}

interface Agency {
  id: number;
  name: string;
}

interface User {
  id: number;
  firstName: string;
  lastName: string;
}

const ManagerForm: React.FC = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    clearErrors,
  } = useForm<UserFormData>({
    defaultValues: {
      role: "",
      agency: "",
      user: "",
    },
  });

  const [agencies, setAgencies] = useState<Agency[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const token = localStorage.getItem("token");

  useEffect(() => {
    const fetchAgencies = async () => {
      try {
        const response = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/api/v1/agency`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        setAgencies(response.data);
      } catch (error) {
        console.error("Error fetching agencies", error);
      }
    };
    fetchAgencies();
  }, [token]);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/users`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        setUsers(response.data);
      } catch (error) {
        console.error("Error fetching users", error);
      }
    };
    fetchUsers();
  }, [token]);

  const onSubmit: SubmitHandler<UserFormData> = async (data) => {
    try {
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/add/member/agency`,
        null,
        {
          params: {
            agencyId: data.agency,
            role: data.role,
            userId: data.user,
          },
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      setSuccessMessage("User added to agency successfully!");
      reset({
        agency: "",
        role: "",
        user: "",
      });
      clearErrors();
    } catch (error: any) {
      console.error(
        "Error adding user to agency:",
        error.response || error.message
      );
      setErrorMessage("Error adding user to agency");
    }
  };

  return (
    <>
      {/* Success Snackbar */}
      <Snackbar
        open={!!successMessage}
        autoHideDuration={4000}
        onClose={() => setSuccessMessage(null)}
      >
        <Alert onClose={() => setSuccessMessage(null)} severity="success">
          {successMessage}
        </Alert>
      </Snackbar>

      {/* Error Snackbar */}
      <Snackbar
        open={!!errorMessage}
        autoHideDuration={4000}
        onClose={() => setErrorMessage(null)}
      >
        <Alert onClose={() => setErrorMessage(null)} severity="error">
          {errorMessage}
        </Alert>
      </Snackbar>

      <Box
        component="form"
        onSubmit={handleSubmit(onSubmit)}
        sx={{ maxWidth: 700, mx: "auto", mt: 4, p: 2, boxShadow: 2 }}
      >
        <Typography variant="h4" component="h1" gutterBottom>
          Create Manager or Collaborator
        </Typography>

        <TextField
          label="Role"
          select
          fullWidth
          margin="normal"
          defaultValue=""
          {...register("role", { required: "Role is required" })}
          error={!!errors.role}
          helperText={errors.role ? errors.role.message : ""}
        >
          <MenuItem value="MANAGER">Manager</MenuItem>
          <MenuItem value="COLLABORATOR">Collaborator</MenuItem>
        </TextField>

        <TextField
          label="Agency"
          select
          fullWidth
          margin="normal"
          defaultValue=""
          {...register("agency", { required: "Agency is required" })}
          error={!!errors.agency}
          helperText={errors.agency ? errors.agency.message : ""}
        >
          {agencies.map((agency) => (
            <MenuItem key={agency.id} value={agency.id}>
              {agency.name}
            </MenuItem>
          ))}
        </TextField>

        <TextField
          label="Select User"
          select
          fullWidth
          margin="normal"
          defaultValue=""
          {...register("user", { required: "User is required" })}
          error={!!errors.user}
          helperText={errors.user ? errors.user.message : ""}
        >
          {users.map((user) => (
            <MenuItem key={user.id} value={user.id}>
              {user.firstName} {user.lastName}
            </MenuItem>
          ))}
        </TextField>

        <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3 }}>
          <Button type="submit" variant="contained" sx={{ width: 150 }}>
            Create
          </Button>
        </Box>
      </Box>
    </>
  );
};

export default ManagerForm;
