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

export interface EditCountryModelProps {
  id?: number;
  en_name?: string;
  hi_name?: string;
  mr_name?: string;
  te_name?: string;
  ta_name?: string;
  bn_name?: string;
  or_name?: string;
  country_code?: string;
  phonecode?: string;
  capital?: string;
  currency?: string;
  currency_name?: string;
  currency_symbol?: string;
}




function EditCountryModel({ rowData, refetch }: { rowData: EditCountryModelProps, refetch: VoidFunction }) {
  const [updateCountry, { isLoading }] = useUpdateCountryMutation()
  const [editData, setEditData] = useState(rowData)
   const [isOpen, setIsOpen] = useState(false);

   useEffect(() => {
   if(rowData){
     setEditData(rowData)
   }
   }, [rowData])
   

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

  const handleSubmit = async () => {
    if (editData?.en_name === '') {
      toaster.create({
        title: "Error",
        description: "Input fields cannot be empty",
        type: "error",
      });
      return;
    }

    // Only en_name is editable, so we only need to send that in the payload.
    const payload = {
      id: rowData?.id,
      en_name: editData?.en_name,
      country_code: rowData?.country_code,
      phonecode: rowData?.phonecode,
      capital: rowData?.capital,
      currency: rowData?.currency,
      currency_name: rowData?.currency_name,
      currency_symbol: rowData?.currency_symbol,
    };

    // console.log('payload', payload)

    try {
      const response = await updateCountry(payload).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "Country updated successfully",
          type: "success",
        });
        setIsOpen(false);
        refetch()
      } else {
        toaster.create({
          title: "Error",
          description: "Failed to update Country",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Error updating template:", error);
      // alert("Failed to update template");
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };


  return (
    <>
      <DialogRoot placement="center" key={editData.id} 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={"auto"}
          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">
                  Country
                </Field.Label>
                <Input
                  value={editData.en_name}
                  onChange={(e) => setEditData({ ...editData, en_name: e.target.value })}
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                />
              </Field.Root>
            </Stack>
          </DialogBody>
          <DialogFooter display="flex" justifyContent="center" pt={"2"}>
            <Button w="100%" bg="#02A0A0" color={"#fff"} onClick={handleSubmit} disabled={isLoading}>
              Save
            </Button>
          </DialogFooter>

          <DialogCloseTrigger color="black" />
        </DialogContent>
      </DialogRoot>
      <Toaster />
    </>
  );
}

export default EditCountryModel;
