import { Button } from "../../../components/ui/button";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
  DialogTitle,
  DialogTrigger,
} from "../../../components/ui/dialog";
import { Field, Input, Stack } from "@chakra-ui/react";
import Edit from "../../../components/ActionIcons/Edit";
import { useEffect, useState } from "react";
import { useUpdateAgencyMasterMutation } from "../../../Redux/Service/agency.master.module.service";
import { Toaster, toaster } from "../../../components/ui/toaster";

// interface Organization {
//   id: number;
//   raid?: string;
//   name: string;
//   auth_signatory?: string;
//   state: string;
//   district?: string;
//   rc_number: number;
//   contact_details?: string;
//   registered_office: string;
//   branch_office?: string;
//   registered_email?: string;
//   other_email?: string;
//   registered_contact?: string;
//   website?: string;
//   domain_name: string;
//   staff_domain_name?: string;
//   gst_number: string;
//   rc_status?: "Active" | "Inactive"; // Assuming it's a status with limited values
// }

type AgencyFormData = {
  id: string;
  name: string;
  state: string;
  rc_number: string;
  registered_office: string;
  domain_name: string;
  gst_number: string;
};



function EditAgencyMaster<T extends AgencyFormData>({ editData, refetch }: { editData: T, refetch: VoidFunction }) {

  const [formData, setFormData] = useState(editData);
  const [isOpen, setIsOpen] = useState(false);
  const [updateAgencyMaster, { isLoading }] = useUpdateAgencyMasterMutation()

  console.log("Edit Data", editData);
  
  useEffect(() => {
    setFormData(editData);
  }, [editData]);

  const handleOpenModal = () => {
    setIsOpen(true);
  };

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

  const handleSubmit = async () => {
    // console.log("Updated Data:", formData);
    if (!formData.name.trim() ||
      !formData.rc_number ||
      !formData.state.trim() ||
      !formData.registered_office.trim() ||
      !formData.domain_name.trim() ||
      !formData.gst_number.trim()) {
      // console.log("Validation failed: Some fields are empty.");
      toaster.create({
        title: "Error",
        description: "Input fields cannot be empty",
        type: "error",
      });
      return;
    }
    setIsOpen(false);
    // Handle API call or further processing here
    const payload = {
      id: formData?.id,
      name: formData?.name,
      state: formData?.state,
      rc_number: formData?.rc_number,
      registered_office: formData?.registered_office,
      domain_name: formData?.domain_name,
      gst_number:formData?.gst_number,
    };

    try {
      const response = await updateAgencyMaster(payload).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "Data updated successfully",
          type: "success",
        });
        refetch()
        setIsOpen(false);
      } else {
        toaster.create({
          title: "Error",
          description: "Failed to update",
          type: "error",
        });
      }
    } catch (error: any) {
      console.error("Error updating template:", error);
      toaster.create({
        title: "Error",
        description: `${error.data.message || "Failed to update"}`,
        type: "error",
      });
      // alert("Failed to update template");
    }
  };

  return (
    <DialogRoot placement="center" open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
      <DialogTrigger asChild>
        <Button bg="transparent" color={"black"} h={"18px"} onClick={handleOpenModal}><Edit /></Button>
      </DialogTrigger>

      <DialogContent
        bg={"#fff"}
        // w={{ lg: "60%", md: "230px" }}
        w={{ base: "90%", md: "400px" }}
        height={"80vh"}
        overflow={"scroll"}
        overflowX="hidden"
        p={3} // Reduced padding
        bgSize={"md"}
      >
        <DialogHeader bg="white">
          <DialogTitle alignSelf="center" color="black" fontSize="14px">
            Edit
          </DialogTitle>
        </DialogHeader>

        <DialogBody bg="white">
          <Stack py={3}>
            <Field.Root>
              <Field.Label color="black" pt={1} fontSize="12px">
                Agency name
              </Field.Label>
              <Input
                name="name"
                value={formData?.name}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                RC No.
              </Field.Label>
              <Input
                name='rc_number'
                value={formData.rc_number}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                State
              </Field.Label>
              <Input
                name="state"
                value={formData.state}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Registered Office Address
              </Field.Label>
              <Input
                name="registered_office"
                value={formData.registered_office}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Website/Domain
              </Field.Label>
              <Input
                name="domain_name"
                value={formData.domain_name}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                GST no.
              </Field.Label>
              <Input
                name="gst_number"
                value={formData.gst_number}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              />

              {/* <Field.Label color="black" pt={1} fontSize="12px">
                RC Status
              </Field.Label>
              <Input
                value={formData.rc_status}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                onChange={handleChange}
              /> */}
            </Field.Root>
          </Stack>
        </DialogBody>
        <DialogFooter display="flex" justifyContent="center" pt={"2"}>
          <Button
            w="100%"
            bg="#02A0A0"
            color={"#fff"}
            fontSize="12px"
            height="30px"
            onClick={handleSubmit}
            disabled={isLoading}
          >
            Save
          </Button>
        </DialogFooter>

        <DialogCloseTrigger color="black" onClick={() => setIsOpen(false)} />
      </DialogContent>
      <Toaster />
    </DialogRoot>
  );
}

export default EditAgencyMaster;
