import { Field, Form, Formik } from "formik";
import FormGroup from "../components/FormGroup";
import type { WifiSettingValues } from "../../../types/types";
import { useWifiAndModem } from "../../../hooks/useCameraWifiandModem";
import { useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { toast, Toaster } from "sonner";

const WiFiSettingsForm = () => {
  const [showPwd, setShowPwd] = useState(false);
  const { wifiQuery, wifiMutation } = useWifiAndModem();

  const wifiSSID = wifiQuery?.data?.propSSID?.value;
  const wifiPassword = wifiQuery?.data?.propPassword?.value;

  const initialValues = {
    ssid: wifiSSID ?? "",
    password: wifiPassword ?? "",
    encryption: "WPA2",
  };

  const validatePassword = (password: string) => {
    if (password.length < 8) {
      toast.error("Password must be at least 8 characters long", { id: "password" });
      return "Password must be at least 8 characters long";
    }
  };

  const handleSubmit = async (values: WifiSettingValues) => {
    const wifiConfig = {
      id: "ModemAndWifiManager-wifi",
      fields: [
        {
          property: "propSSID",
          value: values.ssid,
        },
        {
          property: "propPassword",
          value: values.password,
        },
      ],
    };

    await wifiMutation.mutateAsync(wifiConfig);
  };
  return (
    <>
      <Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
        {({ isSubmitting }) => (
          <Form className="flex flex-col space-y-5 px-2">
            <FormGroup>
              <label htmlFor="ssid" className="font-medium whitespace-nowrap md:w-2/3">
                SSID
              </label>
              <Field
                id="ssid"
                name="ssid"
                type="text"
                className="p-1.5 border border-gray-400 rounded-lg"
                placeholder="Enter SSID"
              />
            </FormGroup>
            <FormGroup>
              <label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
                Password
              </label>
              <div className="flex gap-2 items-center relative mb-4">
                <Field
                  id="password"
                  name="password"
                  type={showPwd ? "text" : "password"}
                  className="p-2 border border-gray-400 rounded-lg w-full"
                  placeholder="Enter Password"
                  validate={validatePassword}
                />

                <FontAwesomeIcon
                  type="button"
                  className="absolute right-5 end-0"
                  onClick={() => setShowPwd((s) => !s)}
                  icon={showPwd ? faEyeSlash : faEye}
                />
              </div>
            </FormGroup>
            <FormGroup>
              <label htmlFor="encryption" className="font-medium whitespace-nowrap md:w-2/3">
                WPA/Encryption Type
              </label>
              <Field
                id="encryption"
                name="encryption"
                className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 w-2/3"
                as="select"
              >
                <option value="WPA2">WPA2</option>
                <option value="WPA3">WPA3</option>
                <option value="WEP">WEP</option>
                <option value="None">None</option>
              </Field>
            </FormGroup>
            <button
              type="submit"
              className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
            >
              {isSubmitting || wifiMutation.isPending ? "Saving..." : " Save WiFi settings"}
            </button>
          </Form>
        )}
      </Formik>
      <Toaster />
    </>
  );
};

export default WiFiSettingsForm;
