"use client";

import { PageContentEditor } from "@/components/dashboard/pages/page-content-editor";
import type {
  PageLocationOption,
  PageUpsertFormValues,
} from "@/components/dashboard/pages/page-upsert-form";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { UnifiedFileUploader } from "@/components/shared/unified-file-uploader";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { Info } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import type { SubmitHandler, UseFormReturn } from "react-hook-form";

interface PageUpsertFormViewProps {
  form: UseFormReturn<PageUpsertFormValues>;
  mode: "create" | "edit";
  onSubmit: SubmitHandler<PageUpsertFormValues>;
  onSecondaryAction: () => void;
}

const TITLE_MAX_LENGTH = 30;
const META_DESCRIPTION_MAX_LENGTH = 325;
const LOCATION_OPTIONS: PageLocationOption[] = ["main", "footer", "support"];

function ToggleOptionField({
  label,
  value,
  onChange,
  enabledLabel,
  disabledLabel,
  isRtl,
}: {
  label: string;
  value: boolean;
  onChange: (value: boolean) => void;
  enabledLabel: string;
  disabledLabel: string;
  isRtl: boolean;
}) {
  return (
    <div className="flex items-center justify-between gap-6">
      <p className={cn("text-base text-foreground", isRtl ? "" : "")}>{label}</p>

      <RadioGroup
        value={value ? "enabled" : "disabled"}
        onValueChange={(nextValue) => onChange(nextValue === "enabled")}
        className="flex items-center gap-6"
      >
        <label className={cn("flex items-center gap-2", isRtl ? "flex-row-reverse" : "flex-row")}>
          <RadioGroupItem value="enabled" className="size-5 rounded-[10px]" />
          <span className="text-sm text-foreground">{enabledLabel}</span>
        </label>

        <label className={cn("flex items-center gap-2", isRtl ? "flex-row-reverse" : "flex-row")}>
          <RadioGroupItem value="disabled" className="size-5 rounded-[10px]" />
          <span className="text-sm text-foreground">{disabledLabel}</span>
        </label>
      </RadioGroup>
    </div>
  );
}

export function PageUpsertFormView({
  form,
  mode,
  onSubmit,
  onSecondaryAction,
}: PageUpsertFormViewProps) {
  const t = useTranslations("dashboard.pages.form");
  const locale = useLocale();
  const isRtl = locale === "ar";
  const labelAlignClass = isRtl ? "" : "";
  const inputAlignClass = isRtl ? "" : "";
  const requiredMessage = t("validation.required");

  const titleLength = (form.watch("title") || "").length;
  const metaDescriptionLength = (form.watch("metaDescription") || "").length;
  const metaImage = form.watch("metaImage");

  const setMetaImage = (file: File | null) => {
    form.setValue("metaImage", file, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true,
    });
  };

  return (
    <Form {...form}>
      <form
        dir={isRtl ? "rtl" : "ltr"}
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-1 gap-6"
      >
        <div className="flex flex-wrap items-center gap-3">
          <Button type="submit" className="h-12 rounded-xl px-5 text-sm font-bold">
            {mode === "create" ? t("actions.create") : t("actions.saveChanges")}
          </Button>

          <Button
            type="button"
            variant="outline"
            className={cn(
              "h-12 rounded-xl px-5 text-sm font-bold",
              mode === "edit" && "border-destructive text-destructive hover:bg-destructive/5"
            )}
            onClick={onSecondaryAction}
          >
            {mode === "create" ? t("actions.preview") : t("actions.cancel")}
          </Button>
        </div>

        <Card className="rounded-2xl border border-border bg-card shadow-none">
          <CardContent className="space-y-6 p-6">
            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
              <FormField
                control={form.control}
                name="title"
                rules={{
                  required: requiredMessage,
                  maxLength: {
                    value: TITLE_MAX_LENGTH,
                    message: t("validation.maxTitle", { max: TITLE_MAX_LENGTH }),
                  },
                }}
                render={({ field }) => (
                  <FormItem className="space-y-2">
                    <FormLabel className={cn("flex items-center gap-2 text-sm text-foreground", labelAlignClass)}>
                      <span>{t("fields.title")}</span>
                      <span className="text-destructive">*</span>
                    </FormLabel>

                    <div className="relative">
                      <FormControl>
                        <Input
                          {...field}
                          maxLength={TITLE_MAX_LENGTH}
                          placeholder={t("placeholders.title")}
                          className={cn("h-12 rounded-xl border-border px-4", inputAlignClass)}
                        />
                      </FormControl>
                      <span
                        className={cn(
                          "pointer-events-none absolute top-1/2 -translate-y-1/2 text-xs text-muted-foreground",
                          isRtl ? "left-3" : "right-3"
                        )}
                      >
                        {t("counters.title", {
                          max: TITLE_MAX_LENGTH,
                          count: titleLength,
                        })}
                      </span>
                    </div>
                    <FormMessage className={labelAlignClass} />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="location"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem className="space-y-2">
                    <FormLabel className={cn("flex items-center gap-2 text-sm text-foreground", labelAlignClass)}>
                      <Info className="h-4 w-4 text-muted-foreground" />
                      <span>{t("fields.location")}</span>
                    </FormLabel>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <FormControl>
                        <SelectTrigger className={cn("h-12 rounded-xl border-border", inputAlignClass)}>
                          <SelectValue placeholder={t("placeholders.location")} />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {LOCATION_OPTIONS.map((option) => (
                          <SelectItem key={option} value={option}>
                            {t(`options.location.${option}`)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage className={labelAlignClass} />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
              <FormField
                control={form.control}
                name="slug"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem className="space-y-2">
                    <FormLabel className={cn("flex items-center gap-2 text-sm text-foreground", labelAlignClass)}>
                      <Info className="h-4 w-4 text-muted-foreground" />
                      <span>{t("fields.slug")}</span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder={t("placeholders.slug")}
                        className={cn("h-12 rounded-xl border-border", inputAlignClass)}
                      />
                    </FormControl>
                    <FormMessage className={labelAlignClass} />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="language"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem className="space-y-2">
                    <FormLabel className={cn("text-sm text-foreground", labelAlignClass)}>
                      {t("fields.language")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <FormControl>
                        <SelectTrigger className={cn("h-12 rounded-xl border-border", inputAlignClass)}>
                          <SelectValue placeholder={t("placeholders.language")} />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="ar">{t("options.language.ar")}</SelectItem>
                        <SelectItem value="en">{t("options.language.en")}</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage className={labelAlignClass} />
                  </FormItem>
                )}
              />
            </div>
          </CardContent>
        </Card>

        <div className="space-y-4">
          <h2 className={cn("text-xl font-bold text-foreground", labelAlignClass)}>
            {t("fields.content")}
          </h2>

          <FormField
            control={form.control}
            name="content"
            rules={{
              validate: (html) => {
                const plain = html
                  .replace(/<[^>]*>/g, " ")
                  .replace(/&nbsp;/g, " ")
                  .trim();
                return plain.length > 0 || t("validation.contentRequired");
              },
            }}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <PageContentEditor
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    placeholder={t("placeholders.content")}
                  />
                </FormControl>
                <FormMessage className={labelAlignClass} />
              </FormItem>
            )}
          />
        </div>

        <Card className="rounded-2xl border border-border bg-card shadow-none">
          <CardContent className="space-y-5 p-6">
            <FormField
              control={form.control}
              name="isPublished"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.status")}
                  value={!!field.value}
                  onChange={field.onChange}
                  enabledLabel={t("options.enabled")}
                  disabledLabel={t("options.disabled")}
                  isRtl={isRtl}
                />
              )}
            />

            <FormField
              control={form.control}
              name="showBreadcrumb"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.showBreadcrumb")}
                  value={!!field.value}
                  onChange={field.onChange}
                  enabledLabel={t("options.enabled")}
                  disabledLabel={t("options.disabled")}
                  isRtl={isRtl}
                />
              )}
            />

            <FormField
              control={form.control}
              name="showTitle"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.showTitle")}
                  value={!!field.value}
                  onChange={field.onChange}
                  enabledLabel={t("options.enabled")}
                  disabledLabel={t("options.disabled")}
                  isRtl={isRtl}
                />
              )}
            />

            <FormField
              control={form.control}
              name="showInNavigation"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.showInNavigation")}
                  value={!!field.value}
                  onChange={field.onChange}
                  enabledLabel={t("options.enabled")}
                  disabledLabel={t("options.disabled")}
                  isRtl={isRtl}
                />
              )}
            />
          </CardContent>
        </Card>

        <Card className="overflow-hidden rounded-2xl border border-border bg-card shadow-none">
          <CardHeader className="border-b border-border py-4">
            <CardTitle className={cn("text-base font-bold text-foreground", labelAlignClass)}>
              {t("seo")}
            </CardTitle>
          </CardHeader>

          <CardContent className="space-y-6 p-6">
            <FormField
              control={form.control}
              name="metaTitle"
              rules={{ required: requiredMessage }}
              render={({ field }) => (
                <FormItem className="space-y-2">
                  <FormLabel className={cn("flex items-center gap-2 text-sm text-foreground", labelAlignClass)}>
                    <Info className="h-4 w-4 text-muted-foreground" />
                    <span>{t("fields.metaTitle")}</span>
                    <span className="text-destructive">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      placeholder={t("placeholders.metaTitle")}
                      className={cn("h-12 rounded-xl border-border", inputAlignClass)}
                    />
                  </FormControl>
                  <FormMessage className={labelAlignClass} />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="metaDescription"
              rules={{
                required: requiredMessage,
                maxLength: {
                  value: META_DESCRIPTION_MAX_LENGTH,
                  message: t("validation.maxMetaDescription", {
                    max: META_DESCRIPTION_MAX_LENGTH,
                  }),
                },
              }}
              render={({ field }) => (
                <FormItem className="space-y-2">
                  <FormLabel className={cn("flex items-center gap-2 text-sm text-foreground", labelAlignClass)}>
                    <Info className="h-4 w-4 text-muted-foreground" />
                    <span>{t("fields.metaDescription")}</span>
                    <span className="text-destructive">*</span>
                  </FormLabel>
                  <div className="relative">
                    <FormControl>
                      <Textarea
                        {...field}
                        maxLength={META_DESCRIPTION_MAX_LENGTH}
                        placeholder={t("placeholders.metaDescription")}
                        className={cn(
                          "min-h-[92px] resize-none rounded-xl border-border pe-4 ps-4 pt-3 pb-8",
                          inputAlignClass
                        )}
                      />
                    </FormControl>
                    <span
                      className={cn(
                        "pointer-events-none absolute bottom-2 text-xs text-muted-foreground",
                        isRtl ? "left-3" : "right-3"
                      )}
                    >
                      {t("counters.remainingChars", {
                        count: META_DESCRIPTION_MAX_LENGTH - metaDescriptionLength,
                      })}
                    </span>
                  </div>
                  <FormMessage className={labelAlignClass} />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="metaImage"
              rules={{ required: requiredMessage }}
              render={() => (
                <FormItem className="space-y-2">
                  <FormLabel className={cn("text-sm text-foreground", labelAlignClass)}>
                    {t("fields.metaImage")} <span className="text-destructive">*</span>
                  </FormLabel>

                  <UnifiedFileUploader
                    multiple={false}
                    accept="image/*"
                    previewVariant="grid"
                    value={metaImage ? [metaImage] : []}
                    onChange={(files) => setMetaImage(files[0] ?? null)}
                    labels={{ browseText: t("upload.browse"), dragText: t("upload.hint"), maxSizeText: t("upload.mediaLibrary") }}
                    useGlobalSettings={false}
                  />

                  <FormMessage className={labelAlignClass} />
                </FormItem>
              )}
            />
          </CardContent>
        </Card>
      </form>
    </Form>
  );
}
