"use client";

import { useEffect, useState } from "react";
import {
  Box,
  Paper,
  Typography,
  TextField,
  MenuItem,
  Button,
  Grid,
} from "@mui/material";
import {
  hospitalSoftwares,
  requestType,
  ticketPriorities,
  ticketStatuses,
} from "@/core/constant";
import { toast } from "react-toastify";
import { handleAxiosError } from "@/core/utils";
import { createTicket } from "@/services/api/ticket.api";
interface DepartmentType {
  id: string;
  slug: string;
  displayName: string;
}
export interface IUserListItem {
  id: string;
  fullname: string;
  nationalCode: string;
  mobile: string;
  roleId: string;
  createdAt: Date;
  updatedAt: Date;
}

export default function TicketForm({
  departments,
  users,
}: {
  departments: DepartmentType[];
  users: IUserListItem[];
}) {
  const [showFieldRelatedSystem, setShowFieldRelatedSystem] = useState(false);
  const [form, setForm] = useState({
    createdBy: "",
    departmentId: "",
    internalPhone: "",
    requestType: "",
    priority: "medium",
    description: "",
    relatedSystem: "",
    location: "",
    helpdeskAction: "",
    assignedTo: "",
    status: "open",
    finalNotes: "",
  });

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

  const handleSubmit = async (e: any) => {
    e.preventDefault();

    try {
      const { message } = await createTicket(form);
      toast.success(message);
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  };

  useEffect(() => {
    if (form.requestType === "1") {
      form.relatedSystem = "";
      setShowFieldRelatedSystem(true);
    } else {
      form.relatedSystem = "";
      setShowFieldRelatedSystem(false);
    }
  }, [form.requestType]);
  return (
    <div className=" h-full w-full">
      <div className="bg-white p-6 rounded-2xl">
        <h5 className="mb-5 text-center text-xl font-bold">فرم تيكت</h5>

        <form onSubmit={handleSubmit}>
          <div className="space-y-5">
            <div className="flex items-center justify-start gap-x-5">
              <TextField
                fullWidth
                label="نام و نام خانوادگي كاربر"
                name="createdBy"
                value={form.createdBy}
                onChange={handleChange}
              />
              <TextField
                select
                fullWidth
                size="medium"
                label="واحد / بخش"
                name="departmentId"
                value={form.departmentId}
                onChange={handleChange}
              >
                {departments.map((dep) => (
                  <MenuItem key={dep.id} value={dep.id}>
                    {dep.displayName}
                  </MenuItem>
                ))}
              </TextField>
              <TextField
                fullWidth
                label="تلفن داخلي"
                name="internalPhone"
                value={form.internalPhone}
                onChange={handleChange}
              />
            </div>

            <div className="flex items-center justify-start gap-x-5">
              <TextField
                select
                fullWidth
                label="نوع درخواست"
                name="requestType"
                value={form.requestType}
                onChange={handleChange}
              >
                {requestType.map((dep) => (
                  <MenuItem key={dep.id} value={dep.id}>
                    {dep.displayName}
                  </MenuItem>
                ))}
              </TextField>
              {showFieldRelatedSystem && (
                <TextField
                  select
                  fullWidth
                  size="medium"
                  label="نرم افزار مرتبط"
                  name="relatedSystem"
                  value={form.relatedSystem}
                  onChange={handleChange}
                >
                  {hospitalSoftwares.map((item) => (
                    <MenuItem value={item.id}>{item.displayName}</MenuItem>
                  ))}
                </TextField>
              )}
              <TextField
                fullWidth
                label="محل وقوع مشكل"
                name="location"
                value={form.location}
                onChange={handleChange}
              />
            </div>

            <div className="flex flex-col gap-y-5">
              <TextField
                multiline
                rows={4}
                fullWidth
                label="توضيحات"
                name="description"
                value={form.description}
                onChange={handleChange}
              />
              <TextField
                multiline
                rows={3}
                fullWidth
                label="اقدام helpdesk"
                name="helpdeskAction"
                value={form.helpdeskAction}
                onChange={handleChange}
              />
            </div>

            <div className="flex items-center justify-start gap-x-5">
              <TextField
                select
                fullWidth
                label="ارجاع به"
                name="assignedTo"
                value={form.assignedTo}
                onChange={handleChange}
              >
                {users.map((dep) => (
                  <MenuItem key={dep.id} value={dep.id}>
                    {dep.fullname}
                  </MenuItem>
                ))}
              </TextField>
              <TextField
                select
                fullWidth
                size="medium"
                label="اولويت درخواست"
                name="priority"
                value={form.priority}
                onChange={handleChange}
              >
                {ticketPriorities?.map((p: any) => (
                  <MenuItem key={p.id} value={p.id}>
                    {p.displayName}
                  </MenuItem>
                ))}
              </TextField>
              <TextField
                select
                fullWidth
                label="وضعيت درخواست"
                name="status"
                value={form.status}
                onChange={handleChange}
              >
                {ticketStatuses?.map((p: any) => (
                  <MenuItem key={p.id} value={p.id}>
                    {p.displayName}
                  </MenuItem>
                ))}
              </TextField>
              
            </div>

            <div>
              <TextField
                multiline
                rows={3}
                fullWidth
                label="توضيحات نهايي"
                name="finalNotes"
                value={form.finalNotes}
                onChange={handleChange}
              />
            </div>

            <Button
              fullWidth
              variant="contained"
              type="submit"
              sx={{
                py: 1.5,
                borderRadius: 3,
                fontSize: 16,
                fontWeight: 600,
                background: "linear-gradient(90deg,#1976d2,#42a5f5,#64b5f6)",
                boxShadow: "0 10px 25px rgba(25,118,210,0.4)",
                "&:hover": {
                  background: "linear-gradient(90deg,#1565c0,#1e88e5,#42a5f5)",
                },
              }}
            >
              ثبت تيكت
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
