import { Formik, Field, Form } from "formik";
import type {
  CameraConfig,
  CameraSettingErrorValues,
  CameraSettingValues,
  ZoomLevel,
} from "../../types/types";
import { useMemo, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-regular-svg-icons";
import CardHeader from "../UI/CardHeader";

type CameraSettingsProps = {
  initialData: CameraConfig;
  updateCameraConfig: (values: CameraSettingValues) => Promise<void> | void;
  zoomLevel?: ZoomLevel;
  onZoomLevelChange?: (level: ZoomLevel) => void;
};

const CameraSettingFields = ({
  initialData,
  updateCameraConfig,
  zoomLevel,
  onZoomLevelChange,
}: CameraSettingsProps) => {
  const [showPwd, setShowPwd] = useState(false);

  const initialValues = useMemo<CameraSettingValues>(
    () => ({
      friendlyName: initialData?.id ?? "",
      cameraAddress: initialData?.propURI?.value ?? "",
      userName: "",
      password: "",
      id: initialData?.id,
      zoom: zoomLevel?.level ? zoomLevel.level : 1,
    }),
    [initialData?.id, initialData?.propURI?.value, zoomLevel?.level]
  );

  const validateValues = (values: CameraSettingValues) => {
    const errors: CameraSettingErrorValues = {};
    if (!values.friendlyName) errors.friendlyName = "Required";
    if (!values.cameraAddress) errors.cameraAddress = "Required";
    if (!values.userName) errors.userName = "Required";
    if (!values.password) errors.password = "Required";

    return errors;
  };

  const handleSubmit = (values: CameraSettingValues) => {
    updateCameraConfig(values);
  };

  const handleRadioButtonChange = (levelNumber: number) => {
    if (!onZoomLevelChange || !zoomLevel) return;
    onZoomLevelChange({
      ...zoomLevel,
      level: zoomLevel?.level !== levelNumber ? levelNumber : zoomLevel?.level,
    });
  };

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validate={validateValues}
      validateOnChange={false}
    >
      {({ errors, touched }) => (
        <Form className="flex flex-col space-y-6 p-2">
          <div className="flex flex-col space-y-2 relative">
            <label htmlFor="friendlyName">Name</label>
            {touched.friendlyName && errors.friendlyName && (
              <small className="absolute right-0 top-0 text-red-500">
                {errors.friendlyName}
              </small>
            )}
            <Field
              id="friendlyName"
              name="friendlyName"
              type="text"
              className="p-2 border border-gray-400 rounded-lg"
              placeholder="Enter camera name"
            />
          </div>

          <div className="flex flex-col space-y-2 relative">
            <label htmlFor="cameraAddress">Camera Address</label>
            {touched.cameraAddress && errors.cameraAddress && (
              <small className="absolute right-0 top-0 text-red-500">
                {errors.cameraAddress}
              </small>
            )}
            <Field
              id="cameraAddress"
              name="cameraAddress"
              type="text"
              className="p-2 border border-gray-400 rounded-lg"
              placeholder="RTSP://..."
              autoComplete="street-address"
            />
          </div>

          <div className="flex flex-col space-y-2 relative">
            <label htmlFor="userName">User Name</label>
            {touched.userName && errors.userName && (
              <small className="absolute right-0 top-0 text-red-500">
                {errors.userName}
              </small>
            )}
            <Field
              id="userName"
              name="userName"
              type="text"
              className="p-2 border border-gray-400 rounded-lg"
              placeholder="Enter user name"
              autoComplete="username"
            />
          </div>

          <div className="flex flex-col space-y-2 relative">
            <label htmlFor="password">Password</label>
            {touched.password && errors.password && (
              <small className="absolute right-0 top-0 text-red-500">
                {errors.password}
              </small>
            )}
            <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"
                autoComplete="new-password"
              />
              <FontAwesomeIcon
                type="button"
                className="absolute right-5 end-0"
                onClick={() => setShowPwd((s) => !s)}
                icon={showPwd ? faEyeSlash : faEye}
              />
            </div>
            <div className="my-3">
              <CardHeader title="Zoom settings" />
              <div className="mx-auto flex gap-10 items-center ">
                <div>
                  <Field
                    type="radio"
                    name="zoom"
                    value={zoomLevel?.level ? zoomLevel.level.toString() : "1"}
                    checked={zoomLevel?.level === 1}
                    className="hidden peer"
                    id="zoom1"
                    onChange={() => handleRadioButtonChange(1)}
                  />
                  <label
                    htmlFor="zoom1"
                    className="px-6 py-2 rounded-md border border-gray-300 peer-checked:border-2 peer-checked:border-blue-900  peer-checked:text-blue-600 peer-checked:bg-gray-100"
                  >
                    x1
                  </label>
                </div>

                <div>
                  <Field
                    type="radio"
                    name="zoom"
                    value={zoomLevel?.level ? zoomLevel.level.toString() : "2"}
                    checked={zoomLevel?.level === 2}
                    className="hidden peer"
                    id="zoom2"
                    onChange={() => handleRadioButtonChange(2)}
                  />
                  <label
                    htmlFor="zoom2"
                    className="px-6 py-2 rounded-md border border-gray-300 peer-checked:border-2 peer-checked:border-blue-900  peer-checked:text-blue-600 peer-checked:bg-gray-100"
                  >
                    x2
                  </label>
                </div>

                <div>
                  <Field
                    type="radio"
                    name="zoom"
                    value={zoomLevel?.level ? zoomLevel.level.toString() : "4"}
                    checked={zoomLevel?.level === 4}
                    className="hidden peer"
                    id="zoom4"
                    onChange={() => handleRadioButtonChange(4)}
                  />
                  <label
                    htmlFor="zoom4"
                    className="px-6 py-2 rounded-md border border-gray-300 peer-checked:border-2 peer-checked:border-blue-900  peer-checked:text-blue-600 peer-checked:bg-gray-100"
                  >
                    x4
                  </label>
                </div>

                <div>
                  <Field
                    type="radio"
                    name="zoom"
                    value={zoomLevel?.level ? zoomLevel.level.toString() : "8"}
                    checked={zoomLevel?.level === 8}
                    className="hidden peer"
                    id="zoom8"
                    onChange={() => handleRadioButtonChange(8)}
                  />
                  <label
                    htmlFor="zoom8"
                    className="px-6 py-2 rounded-md border border-gray-300 peer-checked:border-2 peer-checked:border-blue-900  peer-checked:text-blue-600 peer-checked:bg-gray-100"
                  >
                    x8
                  </label>
                </div>
              </div>
            </div>
            <button
              type="submit"
              className="bg-[#26B170] text-white rounded-lg p-2 mx-auto h-[100%] w-full"
            >
              Save settings
            </button>
          </div>
        </Form>
      )}
    </Formik>
  );
};

export default CameraSettingFields;
