import { FaRegEdit } from "react-icons/fa";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogRoot,
  DialogTrigger,
} from "../../../components/ui/dialog";
import { Box, Field, Stack, Text } from "@chakra-ui/react";
import { Button } from "../../../components/ui/button";
import { useUpdatePrivacyPolicyMutation } from "../../../Redux/Service/privacy.policy.service";
import { Controller, useForm } from "react-hook-form";
import { useState } from "react";
import ReactQuill from "react-quill";

function PrivacyPolicyAddModel({ policyData, refetch }: { policyData: any, refetch: VoidFunction }) {
  const [isOpen, setIsOpen] = useState(false);
  const [updatePrivacyPolicy, { isLoading }] = useUpdatePrivacyPolicyMutation()
  const {
    control,
    handleSubmit,
    reset,
    setValue,
  } = useForm({
    defaultValues: {
      content: "",
      languageCode: "",
    },
  });

  console.log('POLICY', policyData);

  const handleEditClick = (data: any) => {
    setValue("content", data.content); // Pre-fill the content field
    setValue("languageCode", data.privacy_language.language_code); // Pre-fill the language code
    setIsOpen(true); // Open dialog
  };

  const onSubmit = async (formData: any) => {
    if (!formData.content.trim()) return; // Prevent empty updates

    try {
      await updatePrivacyPolicy({
        id: policyData.id,
        content: formData.content,
        language_code: formData.languageCode,
      }).unwrap();
      setIsOpen(false); // Close dialog on success
      reset(); // Reset the form
      refetch()
    } catch (error) {
      console.error("Update failed:", error);
    }
  };

  return (
    <DialogRoot placement="center" open={isOpen}>
      <Box key={policyData.id}>
        <DialogTrigger asChild>
          <Button
            bgColor={"#EEEEEE"}
            pl={3} pr={3}
            size={"xs"}
            color={"#000"}
            onClick={() => handleEditClick(policyData)}
          >
            {" "}
            <FaRegEdit
              color="#000"
              style={{ height: "14px", width: "14px" }}
            />{" "}
            <Text color={"#000"} mt={1}>
              Edit
            </Text>
          </Button>
        </DialogTrigger>
      </Box>

      <DialogContent
        bg={"#fff"}
        minW={'600px'}
        // w={{ base: "90%", md: "400px" }}
        height={"auto"}
        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">
                PrivacyPolicy
              </Field.Label>
              {/* <Textarea
                placeholder=""
                bgColor="#EEEEEE"
                color="black"
                border="none"
                p={2}
                fontSize="12px"
                height={'140px'}
                _focusVisible={{ outline: 'none' }}
                resize={'none'}
              /> */}
              <Controller
                name="content"
                control={control}
                render={({ field }) => (
                  <ReactQuill
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Enter About Us content"
                    modules={{
                      toolbar: [
                        [{ 'header': [1, 2, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        ['link', 'image'],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        ['clean']
                      ],
                    }}
                    formats={[
                      'header',
                      'bold', 'italic', 'underline', 'strike',
                      'list', 'bullet',
                      'link', 'image'
                    ]}
                    style={{ color: "black", border: "none", fontSize: "12px", height: "220px", width: "100%",marginBottom:'20px' }}
                  />
                )}
              />
            </Field.Root>
          </Stack>
        </DialogBody>
        <DialogFooter display="flex" justifyContent="center" pt={"2"}>
          <Button w="100%" bg="#02A0A0" color={"#fff"} mt={'4'} onClick={handleSubmit(onSubmit)} disabled={isLoading}>
            Save
          </Button>
        </DialogFooter>

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

export default PrivacyPolicyAddModel;
