"use client";

import { PageContentEditor } from "@/components/dashboard/pages/page-content-editor";
import type { PageUpsertFormValues } from "@/components/dashboard/pages/page-upsert-form";
import type { PageLocationOption } from "@/components/dashboard/pages/pages-types";
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 { FileUploadDropzone } from "@/components/ui/inputs/file-upload-dropzone";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { PAGE_UPSERT_FORM_ID } from "@/components/dashboard/pages/page-upsert-constants";
import { cn } from "@/lib/utils";
import { ImageIcon, 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";
  locations: PageLocationOption[];
  isSubmitting: boolean;
  onSubmit: SubmitHandler<PageUpsertFormValues>;
}

const TITLE_MAX_LENGTH = 30;
const META_DESCRIPTION_MAX_LENGTH = 325;

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,
  locations,
  isSubmitting,
  onSubmit,
}: 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 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
        id={PAGE_UPSERT_FORM_ID}
        dir={isRtl ? "rtl" : "ltr"}
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-1 gap-6"
      >
        <Card className="rounded-2xl border border-border bg-card shadow-none">
          <CardHeader className="border-b border-border ">
            <CardTitle className={cn("text-base font-bold text-foreground", labelAlignClass)}>
              {t("detailsSection")}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6 p-6">
            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
              <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>
                        {locations.map((option) => (
                          <SelectItem key={option.key} value={option.key}>
                            {locale === "ar" ? option.label.ar : option.label.en}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <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>

            <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>
              )}
            />
          </CardContent>
        </Card>

        <Tabs defaultValue="ar">
          <TabsList className="w-full rounded-t-2xl rounded-b-none border border-b-0 border-border bg-card px-2 -mb-4">
            <TabsTrigger value="ar" className="flex-1">
              {t("options.language.ar")}
            </TabsTrigger>
            <TabsTrigger value="en" className="flex-1">
              {t("options.language.en")}
            </TabsTrigger>
          </TabsList>

          {(["ar", "en"] as const).map((lang) => {
            const dir = lang === "ar" ? "rtl" : "ltr";
            const titleField = lang === "ar" ? "titleAr" : "titleEn";
            const contentField = lang === "ar" ? "contentAr" : "contentEn";
            const titleVal = (form.watch(titleField) ?? "").length;

            return (
              <TabsContent
                key={lang}
                value={lang}
                className="mt-0 rounded-b-2xl rounded-t-none border border-t-0 border-border bg-card"
              >
                <div className="space-y-6 p-6">
                  <FormField
                    control={form.control}
                    name={titleField}
                    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}
                              dir={dir}
                              maxLength={TITLE_MAX_LENGTH}
                              placeholder={t("placeholders.title")}
                              className={cn("h-12 rounded-xl border-border pe-16", inputAlignClass)}
                            />
                          </FormControl>
                          <span
                            className={cn(
                              "pointer-events-none absolute top-1/2 -translate-y-1/2 text-xs text-muted-foreground",
                              lang === "ar" ? "left-3" : "right-3"
                            )}
                          >
                            {t("counters.title", { max: TITLE_MAX_LENGTH, count: titleVal })}
                          </span>
                        </div>
                        <FormMessage className={labelAlignClass} />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="border-t border-border">
                  <FormField
                    control={form.control}
                    name={contentField}
                    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={cn("px-6 pb-4", labelAlignClass)} />
                      </FormItem>
                    )}
                  />
                </div>
              </TabsContent>
            );
          })}
        </Tabs>

        <Card className="rounded-2xl border border-border bg-card shadow-none">
          <CardHeader className="border-b border-border ">
            <CardTitle className={cn("text-base font-bold text-foreground", labelAlignClass)}>
              {t("statusSection")}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-5 p-6">
            <FormField
              control={form.control}
              name="isActive"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.status")}
                  value={field.value ?? false}
                  onChange={field.onChange}
                  enabledLabel={t("options.enabled")}
                  disabledLabel={t("options.disabled")}
                  isRtl={isRtl}
                />
              )}
            />

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

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

            <FormField
              control={form.control}
              name="displayInNavbar"
              render={({ field }) => (
                <ToggleOptionField
                  label={t("fields.showInNavigation")}
                  value={field.value ?? false}
                  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 ">
            <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>

                  <FileUploadDropzone
                    file={metaImage}
                    onFileChange={setMetaImage}
                    accept="image/*"
                    uploadHint={t("upload.hint")}
                    browseLabel={t("upload.browse")}
                    helperText={t("upload.mediaLibrary")}
                    icon={<ImageIcon className="h-6 w-6 text-primary" />}
                    iconWrapperClassName="bg-[var(--stat-gold-bg)]"
                    dropzoneClassName="rounded-lg border-border bg-card"
                    minHeightClassName="min-h-[162px]"
                  />

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