import { Formik, Form, Field, FieldArray } from "formik";
import { useSystemSettings } from "../hooks/useSystemSettings";
import type { NetworkConfig, SystemSettings } from "../../../types/types";
import { toast } from "sonner";
import { useGetNetworkConfig } from "../hooks/useGetNetworkConfig";

const SystemConfig = () => {
  const { systemSettingsQuery, systemSettingsMutation } = useSystemSettings();
  const { networkConfigQuery, networkConfigMutation } = useGetNetworkConfig();

  const isLoading = networkConfigMutation?.isPending || networkConfigMutation?.isPending;
  const isGettingLoading = systemSettingsQuery?.isLoading || networkConfigQuery?.isLoading;
  const timeZoneOptions = systemSettingsQuery?.data?.propLocalTimeZone?.accepted;
  const timeZoneOpts = timeZoneOptions?.split(",").map((option: string) => option.trim().replace(/\[|\]/g, ""));
  const timeSourceOptions = systemSettingsQuery?.data?.propTimeSource?.accepted;
  const timeSourceOpts = timeSourceOptions?.split(",").map((option: string) => option.trim().replace(/\[|\]/g, ""));
  const deviceName = systemSettingsQuery?.data?.propDeviceName?.value;
  const timeZone = systemSettingsQuery?.data?.propLocalTimeZone?.value;
  const SNTPServer = systemSettingsQuery?.data?.propSNTPServer?.value;
  const SNTPInterval = systemSettingsQuery?.data?.propSNTPIntervalMinutes?.value;
  const timeSource = systemSettingsQuery?.data?.propTimeSource?.value;
  const primaryServer = networkConfigQuery?.data?.propNameServerPrimary?.value;
  const secondaryServer = networkConfigQuery?.data?.propNameServerSecondary?.value;
  const ipAddress = networkConfigQuery?.data?.propHost?.value;
  const subnetMask = networkConfigQuery?.data?.propNetmask?.value;
  const gateway = networkConfigQuery?.data?.propGateway?.value;

  const initialValues = {
    deviceName: deviceName ?? "",
    timeZone: timeZone ?? "",
    localTimeZone: timeZone ?? "",
    SNTPServer: SNTPServer ?? "",
    SNTPInterval: SNTPInterval ?? 60,
    SNTPIntervalMinutes: SNTPInterval ?? 60,
    primaryServer: primaryServer ?? "",
    secondaryServer: secondaryServer ?? "",
    timeSource: timeSource ?? "",
    ipAddress: ipAddress ?? "",
    subnetMask: subnetMask ?? "",
    gateway: gateway ?? "",
    customFields: [],
  };

  const handleSubmit = async (values: SystemSettings & NetworkConfig) => {
    const result = await systemSettingsMutation.mutateAsync(values);
    const networkResult = await networkConfigMutation.mutateAsync({
      ipAddress: values.ipAddress,
      subnetMask: values.subnetMask,
      gateway: values.gateway,
      primaryServer: values.primaryServer,
      secondaryServer: values.secondaryServer,
    });

    if (result.id && networkResult.id) {
      toast.success("System settings updated successfully");
    } else {
      toast.error("Failed to update system settings");
    }
  };

  if (isGettingLoading) {
    return <div>Loading...</div>;
  }

  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
      {({ values }) => (
        <Form className="flex flex-col space-y-4">
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="deviceName">Device Name</label>
            <Field
              name="deviceName"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter device name"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="timeZone">Timezone</label>
            <Field
              name="timeZone"
              as="select"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs bg-[#253445] "
              autoComplete="off"
            >
              {timeZoneOpts?.map((option: string) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </Field>
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="timeSource">Time Source</label>
            <Field
              name="timeSource"
              as="select"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs bg-[#253445] "
              autoComplete="off"
            >
              {timeSourceOpts?.map((option: string) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </Field>
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="SNTPServer">SNTP Server</label>
            <Field
              name="SNTPServer"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter SNTP server"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="SNTPInterval">SNTP Interval</label>
            <Field
              name="SNTPInterval"
              type="number"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter SNTP interval"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="subnetMask">Subnet Mask</label>
            <Field
              name="subnetMask"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter subnet mask"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="ipAddress">IP Address</label>
            <Field
              name="ipAddress"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter IP address"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="gateway">Gateway</label>
            <Field
              name="gateway"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter gateway"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="primaryServer">Primary DNS Server</label>
            <Field
              name="primaryServer"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter primary DNS server"
              autoComplete="off"
            />
          </div>
          <div className="flex flex-col md:flex-row space-y-4 justify-between">
            <label htmlFor="secondaryServer">Secondary DNS Server</label>
            <Field
              name="secondaryServer"
              type="text"
              className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
              placeholder="Enter secondary DNS server"
              autoComplete="off"
            />
          </div>
          <div className="border-b border-gray-500 my-3">
            <h2 className="font-bold">Custom Fields</h2>
          </div>
          <div className="items-center mb-4">
            <FieldArray name="customFields">
              {(arrayHelpers) => (
                <>
                  {values.customFields.map((_, index) => (
                    <div key={index} className="flex flex-row justify-between items-center mb-4">
                      <label htmlFor={`customFields.${index}`} className="mr-2">
                        Custom Field {index + 1}
                      </label>
                      <Field
                        name={`customFields.${index}`}
                        key={index}
                        className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
                        placeholder={`Enter Custom Field ${index + 1}`}
                        autoComplete="off"
                      />
                    </div>
                  ))}
                  <button
                    type="button"
                    onClick={() => arrayHelpers.push("")}
                    className="mr-2 border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer"
                  >
                    Add Custom Field
                  </button>
                  {values.customFields.length > 0 && (
                    <button
                      type="button"
                      onClick={() => arrayHelpers.pop()}
                      className="border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer"
                    >
                      Remove Custom Field
                    </button>
                  )}
                </>
              )}
            </FieldArray>
          </div>
          <button
            type="submit"
            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"
            disabled={isLoading}
          >
            {isLoading ? "Saving..." : "Save Settings"}
          </button>
        </Form>
      )}
    </Formik>
  );
};

export default SystemConfig;
