"use client";

import { useWatch, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormFieldGroup,
  FormGrid,
  FormSection,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useSocialMediaMutations } from "@/hooks/use-social-media";
import type { SocialPlatform } from "@/types";

import {
  getSocialMediaFieldLabel,
  getSocialMediaFieldPlaceholder,
  linkViaApiSchema,
  platformFields,
  platforms,
  type ApiLinkPlatform,
  type LinkViaApiFormValues,
} from "./link-via-api-form";

interface LinkViaApiDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess?: () => void;
}

export function LinkViaApiDialog({
  open,
  onOpenChange,
  onSuccess,
}: LinkViaApiDialogProps) {
  const t = useTranslations();
  const { connectAccount, verifyAccount, isLoading } = useSocialMediaMutations();

  const form = useForm<LinkViaApiFormValues>({
    resolver: zodResolver(linkViaApiSchema),
    defaultValues: {
      platform: undefined as unknown as LinkViaApiFormValues["platform"],
      settings: {},
    },
  });

  const selectedPlatform = useWatch({
    control: form.control,
    name: "platform",
  });

  const currentFields = selectedPlatform
    ? platformFields[selectedPlatform]
    : [];

  const handlePlatformChange = (value: string) => {
    form.setValue("platform", value as ApiLinkPlatform, {
      shouldDirty: true,
      shouldValidate: true,
    });
    form.setValue("settings", {}, { shouldDirty: true });
    form.clearErrors("settings");
  };

  const handleClose = () => {
    form.reset({
      platform: undefined as unknown as LinkViaApiFormValues["platform"],
      settings: {},
    });
    onOpenChange(false);
  };

  const onSubmit = async (data: LinkViaApiFormValues) => {
    try {
      await connectAccount({
        platform: data.platform as SocialPlatform,
        credentials: data.settings,
      });

      handleClose();
      onSuccess?.();
    } catch {
      // Error toast is handled by the mutation hook.
    }
  };

  const handleVerify = async () => {
    const isValid = await form.trigger();
    if (!isValid) {
      return;
    }

    const values = form.getValues();
    try {
      await verifyAccount({
        platform: values.platform as SocialPlatform,
        credentials: values.settings,
      });
    } catch {
      // Error toast is handled by the mutation hook.
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[650px] max-h-[60vh]">
        <DialogHeader>
          <DialogTitle>{t("socialMedia.linkViaAPI")}</DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex min-h-0 flex-1 flex-col"
          >
            <DialogBody className="space-y-6">
            <FormSection>
              <FormField
                control={form.control}
                name="platform"
                render={({ field }) => (
                  <FormFieldGroup
                    label={t("socialMedia.platform")}
                    required
                  >
                    <Select
                      value={field.value}
                      onValueChange={handlePlatformChange}
                    >
                      <FormControl>
                        <SelectTrigger id="dialog-platform" className="h-10">
                          <SelectValue
                            placeholder={t("socialMedia.selectPlatform")}
                          />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {platforms.map((platform) => (
                          <SelectItem
                            key={platform.value}
                            value={platform.value}
                          >
                            {t(`socialMedia.platforms.${platform.labelKey}`)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FormFieldGroup>
                )}
              />
            </FormSection>

            {selectedPlatform && currentFields.length > 0 ? (
              <FormSection title={t("socialMedia.platformCredentials")}>
                <FormGrid className="gap-4 md:grid-cols-2">
                  {currentFields.map((platformField) => (
                    <FormField
                      key={platformField.key}
                      control={form.control}
                      name={`settings.${platformField.key}` as const}
                      render={({ field }) => (
                        <FormFieldGroup
                          label={getSocialMediaFieldLabel(
                            t,
                            platformField.key,
                          )}
                          required={platformField.required}
                        >
                          <FormControl>
                            <Input
                              {...field}
                              type={platformField.type || "text"}
                              placeholder={getSocialMediaFieldPlaceholder(
                                t,
                                platformField.key,
                              )}
                              className="h-10"
                            />
                          </FormControl>
                        </FormFieldGroup>
                      )}
                    />
                  ))}
                </FormGrid>
              </FormSection>
            ) : null}

            </DialogBody>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleVerify}
                disabled={isLoading || !selectedPlatform}
              >
                {t.has("socialMedia.verifyCredentials")
                  ? t("socialMedia.verifyCredentials")
                  : "Verify credentials"}
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                disabled={isLoading}
              >
                {t("common.cancel")}
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading ? t("common.loading") : t("common.save")}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
