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

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

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

  const createApiService = useAdmin((state) => state.createApiService);

  const credentials = useAdmin((state) => state.createdCredentials);

  const onSubmit = useCallback(
    (data: FormData) => {
      console.log("Form submitted:", data);
      createApiService({
        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"],
        is_active: data.enabled,
      });
    },
    [createApiService],
  );

  return (
    <div className="p-4">
      {credentials !== null && <ApiServiceCredentialsModal />}

      <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">
              Final Customization & Submit
            </h2>
          </div>
          <div className="p-4">
            <label className="inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                className="sr-only peer"
                {...register("enabled")}
              />
              <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600 dark:peer-checked:bg-blue-600"></div>
              <span className="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300">
                Enabled by default
              </span>
            </label>

            <div className="flex flex-row items-center justify-between gap-2 mt-4">
              <Button type="submit">Create</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 ApiServiceCreatePage;
