import Breadcrumbs from "@/components/ui/breadcrumbs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import ApiServiceUpdatedModal from "@/feature/ApiServiceUpdatedModal";
import { useApiServices } from "@/store/admin/apiServices";
import { useCallback, useEffect, type FC } from "react";
import { useForm } from "react-hook-form";
import { Link, useParams } from "react-router";

interface FormData {
  name: string;
  description: string;
  redirectUris: string;
  scopes: string;
  grantTypes: string;
}

const ApiServiceEditPage: FC = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<FormData>({
    defaultValues: {
      scopes: "openid",
    },
  });

  const { serviceId } = useParams();
  const apiService = useApiServices((state) => state.view);

  const loadService = useApiServices((state) => state.fetchSingle);

  const updateApiService = useApiServices((state) => state.update);
  const updating = useApiServices((state) => state.updating);
  const updated = useApiServices((state) => state.updated);

  const onSubmit = useCallback(
    (data: FormData) => {
      console.log("Form submitted:", data);
      updateApiService({
        name: data.name,
        description: data.description ?? "",
        redirect_uris: data.redirectUris.trim().split("\n"),
        scopes: data.scopes.trim().split(" "),
        grant_types: data.grantTypes
          ? data.grantTypes.trim().split(" ")
          : ["authorization_code"],
      });
    },
    [updateApiService],
  );

  useEffect(() => {
    if (typeof serviceId === "string") loadService(serviceId);
  }, [loadService, serviceId]);

  useEffect(() => {
    if (apiService != null) {
      setValue("name", apiService.name);
      setValue("description", apiService.description);
      setValue("redirectUris", apiService.redirect_uris.join("\n"));
      setValue("scopes", apiService.scopes.join(" "));
      setValue("grantTypes", apiService.grant_types.join(" "));
    }
  }, [apiService, setValue]);

  return (
    <div className="p-4">
      {updated && <ApiServiceUpdatedModal />}

      <Breadcrumbs
        items={[
          { href: "/admin", label: "Admin" },
          { href: "/admin/api-services", label: "API Services" },
          { label: "Create new API Service" },
        ]}
      />
      <form onSubmit={handleSubmit(onSubmit)}>
        {/* Service Information */}
        <div className="border dark:border-gray-800 border-gray-300 rounded mt-4 flex flex-col">
          <div className="p-4 border-b dark:border-gray-800 border-gray-300">
            <h2 className="text-gray-800 dark:text-gray-200">
              Service Information
            </h2>
          </div>
          <div className="p-4">
            <div className="flex flex-col gap-2 mb-4">
              <p className="text-gray-600 dark:text-gray-400 text-sm">Name</p>
              <Input
                placeholder="Display Name"
                {...register("name", { required: "Name is required" })}
              />
              {errors.name && (
                <span className="text-red-500 text-sm">
                  {errors.name.message}
                </span>
              )}
            </div>

            <div className="flex flex-col gap-2 mb-4">
              <p className="text-gray-600 dark:text-gray-400 text-sm">
                Description
              </p>
              <textarea
                {...register("description", {
                  required: "Description is required",
                })}
                className="dark:text-gray-100 border border-gray-300 dark:border-gray-700 rounded placeholder:text-gray-600 text-sm p-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="Some description goes here..."
              ></textarea>
              {errors.description && (
                <span className="text-red-500 text-sm">
                  {errors.description.message}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* OpenID Connect */}
        <div className="border dark:border-gray-800 border-gray-300 rounded mt-4 flex flex-col">
          <div className="p-4 border-b dark:border-gray-800 border-gray-300">
            <h2 className="text-gray-800 dark:text-gray-200">OpenID Connect</h2>
          </div>
          <div className="p-4">
            <div className="flex flex-col gap-2 mb-4">
              <p className="text-gray-600 dark:text-gray-400 text-sm">
                Redirect URIs
              </p>
              <textarea
                {...register("redirectUris", {
                  required: "At least one URI is required",
                })}
                className="dark:text-gray-100 border border-gray-300 dark:border-gray-700 rounded placeholder:text-gray-600 text-sm p-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="Enter multiple URIs separated with new line"
              ></textarea>
              {errors.redirectUris && (
                <span className="text-red-500 text-sm">
                  {errors.redirectUris.message}
                </span>
              )}
            </div>

            <div className="flex flex-col gap-2 mb-4">
              <p className="text-gray-600 dark:text-gray-400 text-sm">Scopes</p>
              <Input
                placeholder="Scopes separated with space"
                {...register("scopes", { required: "Scopes are required" })}
              />
              {errors.scopes && (
                <span className="text-red-500 text-sm">
                  {errors.scopes.message}
                </span>
              )}
            </div>

            <div className="flex flex-col gap-2 mb-4">
              <p className="text-gray-600 dark:text-gray-400 text-sm">
                Grant Types
              </p>
              <Input
                placeholder="Leave empty for 'authorization_code'"
                {...register("grantTypes")}
              />
            </div>
          </div>
        </div>

        {/* Final Section */}
        <div className="border dark:border-gray-800 border-gray-300 rounded mt-4 flex flex-col">
          <div className="p-4 border-b dark:border-gray-800 border-gray-300">
            <h2 className="text-gray-800 dark:text-gray-200">
              Approve & Submit
            </h2>
          </div>
          <div className="p-4">
            <div className="flex flex-row items-center justify-between gap-2 mt-4">
              <Button type="submit" loading={updating}>
                Update
              </Button>
              <Link to="/admin/api-services">
                <Button
                  variant="text"
                  className="text-red-400 hover:text-red-500"
                >
                  Cancel
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </form>
    </div>
  );
};

export default ApiServiceEditPage;
