import { Field, useFormikContext } from "formik";
import { useOSDConfig } from "../hooks/useOSDConfig";
import OSDFieldToggle from "./OSDFieldToggle";
import type { OSDConfigFields } from "../../../types/types";
import { toast } from "sonner";

type OSDFieldsProps = {
  isOSDLoading: boolean;
};

const OSDFields = ({ isOSDLoading }: OSDFieldsProps) => {
  const { osdMutation } = useOSDConfig();
  const { values } = useFormikContext<OSDConfigFields>();

  const includeKeys = Object.keys(values as OSDConfigFields).filter((value) => value.includes("include"));

  const handleSubmit = async (values: OSDConfigFields) => {
    const result = await osdMutation.mutateAsync(values);
    if (result?.id) {
      toast.success("OSD Config updated successfully");
    }
  };

  if (isOSDLoading) {
    return <div>Loading OSD Options...</div>;
  }

  return (
    <div>
      <div className="flex flex-col space-y-4">
        <div className="p-4 border border-gray-600 rounded-lg flex flex-col space-y-4">
          <div className="flex flex-col space-y-4">
            {includeKeys.map((key) => (
              <OSDFieldToggle key={key} value={key} label={key.replace("include", "Include ")} />
            ))}
          </div>
          <div className="flex flex-row justify-between">
            <label htmlFor="overlayPosition">Overlay Position</label>
            <Field
              as="select"
              name="overlayPosition"
              className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
            >
              <option value="Top">Top</option>
              <option value="Bottom">Bottom</option>
            </Field>
          </div>
          <div className="flex flex-row justify-between">
            <label htmlFor="OSDTimestampFormat">OSD Timestamp Format</label>
            <Field
              as="select"
              name="OSDTimestampFormat"
              className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
            >
              <option value="UTC">UTC</option>
              <option value="LOCAL">Local</option>
            </Field>
          </div>
          <button
            type="button"
            onClick={() => handleSubmit(values)}
            className="w-full md:w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
          >
            Save Settings
          </button>
        </div>
      </div>
    </div>
  );
};

export default OSDFields;
