import { Label } from "flowbite-react";
import { useSession } from "next-auth/react";
import dynamic from "next/dynamic";
import { FC, useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import UniqueField from "../common/unique-field";
import { InputField, Radio, Select, Textarea } from "../forms/Inputs";
import { TSclientSchema } from "../forms/schema/client";
import ActionButton from "../action-button";
import Spinner from "../spinner";
import { toast } from "react-toastify";
const DropdownList = dynamic(() => import("../common/Dropdown"));

type props = {
  client: TSclientSchema;
  isEdit?: boolean
};
const BasicForm: FC<props> = ({ client, isEdit = false }) => {
  const [loading, setLoading] = useState(false);
  const { data: session }: any = useSession();
  const [networkId, setNetwork] = useState<string | number | undefined>(
    undefined
  );
  const [zoneId, setZone] = useState<string | number | undefined>(undefined);
  const {
    formState: { errors },
    setValue,
  } = useFormContext();

  const handleGetLocation = () => {
    setLoading(true);

    if (!navigator.geolocation) {
      toast.error('Geolocation is not supported by your browser.');
      setLoading(false);
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        setValue('adr_latitude', position.coords.latitude);
        setValue('adr_longitude', position.coords.longitude);
        setLoading(false);
      },
      (err) => {
        toast.error(`Error getting location: ${err.message}`);
        setLoading(false);
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0,
      }
    );
  };

  const paymentDeadLine = () => {
    const label = (item: number): string => {
      let label: string = "None";
      if (item > 0 && item < 10) {
        label = `0${item}`;
      }
      if (item > 9) {
        label = item?.toString();
      }
      return label;
    };
    return Array.from(Array(31).keys()).map((item) => ({
      value: item,
      label: label(item),
    }));
  };

  useEffect(() => {
    if (session?.user?.reseller_id && client?.network) {
      setValue("network_id", client?.network?.id);
    }
  }, [client, session]);

  return (
    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
      <div className="left">
        <div className="mt-1">
          <InputField
            labelText="Client name"
            name="name"
            placeholder="Client Name"
            mandatory={true}
            errors={errors}
          />
        </div>
        <div className="mt-1">
          <UniqueField
            mandatory={true}
            labelText="Client ID / PPPoE ID"
            name="pppoe_username"
            placeholder="Ex: abc@017896354859"
            message="PPPoE ID"
            fieldId={client?.id}
          />
        </div>
        <div className="mt-3">
          <InputField
            mandatory={true}
            labelText="Password"
            name="pppoe_password"
            placeholder="password"
            errors={errors}
          />
        </div>
        <div className="mt-4">
          <InputField
            labelText="Mobile Number"
            name="phone"
            placeholder="88"
            errors={errors}
          />
        </div>
        <div className="mt-1">
          <InputField
            labelText="IP Address"
            name="ip_address"
            placeholder="ex: xxx.xxxx.xx.xx"
            errors={errors}
          />
        </div>
        <div className="mt-1">
          <InputField
            labelText="Discount"
            name="discount"
            placeholder="0.00"
            errors={errors}
          />
        </div>
        <div className="mt-3">
          <Radio
            groupLabel="Send welcome SMS"
            name="welcome_notification"
            options={[
              { label: "Yes", value: 1 },
              { label: "No", value: 0 },
            ]}
            defaultValue={client?.welcome_notification ?? 1}
          />
        </div>
        <div className="mt-1">
          <Select
            labelText="Payment deadline"
            defaultOption={client?.payment_deadline}
            defaultValue={client?.payment_deadline ?? 0}
            name="payment_deadline"
            options={paymentDeadLine()}
          />
        </div>
        <div className="mt-1">
          <Select
            labelText="Payment Term"
            defaultValue={1}
            name="payment_term"
            options={Array.from(Array(12).keys()).map((item) => ({
              value: item + 1,
              label: item + 1,
            }))}
          />
        </div>
        <div className="mt-1">
          <div className="flex items-center gap-2">
            <Radio
              groupLabel="Billing Term"
              name="billing_term"
              options={[
                { label: "Prepaid", value: "prepaid" },
                { label: "Postpaid", value: "postpaid" },
              ]}
              defaultValue={client?.billing_term ?? "prepaid"}
            />
          </div>
        </div>
        <div className="mt-1">
          <Textarea
            rows={3}
            labelText="Current Address"
            name="current_address"
            placeholder="Address"
            errors={errors}
          />
        </div>
      </div>
      <div className="right">
        <div className="mt-2">
          <Label className="mb-2 block">Zone</Label>
          <DropdownList
            defaultItems={client?.zone}
            name="zone"
            idName="zone_id"
            getLabel={(zone: any) => zone.name}
            isMulti={false}
            onChange={(zone) => setZone(zone.value)}
          />
        </div>
        <div className="mt-3">
          <Label className="mb-2 block">Sub Zone</Label>
          <DropdownList
            defaultItems={client?.sub_zone}
            name="sub_zone"
            idName="sub_zone_id"
            getLabel={(sub_zone: any) => sub_zone.name}
            isMulti={false}
            isEnabled={client?.sub_zone ? true : false}
            depend_on={zoneId ? zoneId : client?.zone?.id}
          />
        </div>
        {session?.user?.reseller_id ? (
          <>
            <div className="mt-1">
              <div className="mb-2 mt-3">
                <Label>Network Packages (Mikrotik)</Label>
              </div>
              <DropdownList
                name="package"
                idName="package_id"
                getLabel={(mikrotik) => mikrotik.name}
                isMulti={false}
                defaultItems={client?.package}
                setOriginalValue={(packages) =>
                  setValue("network_id", packages.network_id)
                }
              />
            </div>
          </>
        ) : (
          <>
            <div className="mt-3">
              <Label className="mb-2 block">
                Network
                <span className="text-red-500">*</span>
              </Label>
              <DropdownList
                defaultItems={client?.network}
                name="network"
                idName="network_id"
                getLabel={(network: any) => network.name}
                isMulti={false}
                onChange={(network) => setNetwork(network?.value)}
              />
            </div>

            <div className="mt-1">
              <div className="mb-2 mt-3">
                <Label>Network Packages (Mikrotik)</Label>
              </div>
              <DropdownList
                name="network_package"
                idName="package_id"
                getLabel={(mikrotik) => mikrotik.name}
                isMulti={false}
                isEnabled={client?.package ? true : false}
                depend_on={client?.package ? undefined : networkId}
                defaultItems={client?.package}
              />
            </div>
            <div className="mt-4">
              <Label className="mb-2 block">
                Device
              </Label>
              <DropdownList
                defaultItems={client?.device}
                name="device"
                idName="device_id"
                placeholder="Device"
                getLabel={(device: any) => device?.name}
                isMulti={false}
                onChange={(network) => setNetwork(network?.value)}
              />
            </div>
          </>
        )}
        <div className="mt-3">
          <Radio
            groupLabel="Billing Type"
            name="billing_type"
            options={[
              { label: "Auto", value: "auto" },
              { label: "Manual", value: "manual" },
              { label: "No bill", value: "no_bill" },
            ]}
            defaultValue={client?.billing_type ?? "auto"}
          />
        </div>
        <div className="mt-1">
          <InputField
            labelText="National ID No"
            name="nid"
            placeholder="ex: NID Number"
            errors={errors}
          />
        </div>
        {!isEdit && (
          <div className="mt-1">
            <Select
              defaultValue={1}
              options={[
                { value: 1, label: "Active" },
                { value: 0, label: "Inactive" },
              ]}
              labelText="Status"
              name="status"
              errors={errors}
            />
          </div>

        )}
        <div className="mt-1">
          <Textarea
            rows={3}
            labelText="Notes"
            name="note"
            placeholder="Optional"
            errors={errors}
          />
        </div>
        <div className="mt-1">
          <div className="flex gap-6">
            <Label>Latitude</Label>
            {loading ? <Spinner size="sm" color="purple" /> :
              <div className="font-normal text-blue-500 cursor-pointer" onClick={() => handleGetLocation()}>Get Location</div>
            }
          </div>
          <InputField
            name="adr_latitude"
            placeholder="ex: 1283490"
            errors={errors}
          />
        </div>
        <div className="mt-1">
          <InputField
            labelText="Longitude"
            name="adr_longitude"
            placeholder="ex: 459506"
            errors={errors}
          />
        </div>
      </div>
    </div>
  );
};

export default BasicForm;
