"use client";

import type { ArticleUpsertFormValues, DashboardArticleCategory, DashboardArticleTag } from "@/components/dashboard/blogs/articles-types";
import { LexicalRichTextEditor } from "@/components/lexical/lexical-rich-text-editor";
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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { Info, Loader2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import type { SubmitHandler, UseFormReturn } from "react-hook-form";

interface BlogUpsertFormViewProps {
  form: UseFormReturn<ArticleUpsertFormValues>;
  mode: "create" | "edit";
  categories: DashboardArticleCategory[];
  tags: DashboardArticleTag[];
  onSubmit: SubmitHandler<ArticleUpsertFormValues>;
  onSaveDraft: () => void;
}

const STATUS_VALUES = ["published", "disabled", "scheduled", "draft"] as const;

export function BlogUpsertFormView({
  form,
  mode,
  categories,
  tags,
  onSubmit,
  onSaveDraft,
}: BlogUpsertFormViewProps) {
  const t = useTranslations("dashboard.blogs.form");
  const locale = useLocale();
  const isRtl = locale === "ar";

  const requiredMessage = t("validation.required");
  const featuredImage = form.watch("featured_image");
  const metaImage = form.watch("meta_image");
  const publishType = form.watch("publish_type");
  const isSubmitting = form.formState.isSubmitting;

  const setFileValue = (field: "featured_image" | "meta_image", file: File | null) => {
    form.setValue(field, 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 xl:grid-cols-[minmax(0,1fr)_300px]"
      >
        {/* ── Main column ── */}
        <div className="flex min-w-0 flex-col gap-6">

          {/* Title + excerpt */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardContent className="space-y-5 p-6">
              <FormField
                control={form.control}
                name="title"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("fields.title")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input {...field} placeholder={t("placeholders.title")} className="h-12 rounded-xl border-border" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="excerpt"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("fields.description")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <FormControl>
                      <Textarea
                        {...field}
                        placeholder={t("placeholders.description")}
                        className="min-h-[120px] resize-none rounded-xl border-border"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* Body / rich text */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("fields.content")}</CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              <FormField
                control={form.control}
                name="body"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <LexicalRichTextEditor
                        value={field.value || ""}
                        onChange={field.onChange}
                        placeholder={t("placeholders.content")}
                        dir={isRtl ? "rtl" : "ltr"}
                        namespace="BlogEditor"
                        minHeight={320}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* Additional data */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("sections.additionalData")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-5 p-6">
              <FormField
                control={form.control}
                name="source"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.source")}</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder={t("placeholders.source")} className="h-11 rounded-xl border-border" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="slug"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex items-center gap-2">
                      <FormLabel className="text-sm text-foreground">{t("fields.slug")}</FormLabel>
                      <Info className="size-4 text-muted-foreground" />
                    </div>
                    <FormControl>
                      <Input {...field} dir="ltr" placeholder={t("placeholders.slug")} className="h-11 rounded-xl border-border" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Tag pills */}
              <FormField
                control={form.control}
                name="tag_ids"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.tags")}</FormLabel>
                    <div className="flex flex-wrap gap-2 pt-1">
                      {tags.map((tag) => {
                        const current = field.value ?? [];
                        const selected = current.includes(tag.id);
                        return (
                          <button
                            key={tag.id}
                            type="button"
                            onClick={() => {
                              field.onChange(
                                selected ? current.filter((id) => id !== tag.id) : [...current, tag.id]
                              );
                            }}
                            className={cn(
                              "rounded-xl px-3 py-1.5 text-sm transition-colors",
                              selected
                                ? "bg-primary text-primary-foreground"
                                : "bg-muted text-muted-foreground hover:bg-muted/70"
                            )}
                          >
                            {tag.name}
                          </button>
                        );
                      })}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="is_featured"
                render={({ field }) => (
                  <FormItem className="flex items-center gap-3">
                    <FormControl>
                      <Switch checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                    <FormLabel className="mb-0 cursor-pointer text-sm text-foreground">{t("fields.featured")}</FormLabel>
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* SEO */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("sections.seo")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-5 p-6">
              <FormField
                control={form.control}
                name="meta_title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.metaTitle")}</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder={t("placeholders.metaTitle")} className="h-11 rounded-xl border-border" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="meta_description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.metaDescription")}</FormLabel>
                    <FormControl>
                      <Textarea
                        {...field}
                        placeholder={t("placeholders.metaDescription")}
                        className="min-h-[120px] resize-none rounded-xl border-border"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="meta_image"
                render={() => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.metaImage")}</FormLabel>
                    <UnifiedFileUploader
                      multiple={false}
                      accept="image/*"
                      previewVariant="grid"
                      value={metaImage instanceof File ? [metaImage] : []}
                      externalPreviewItems={typeof metaImage === "string" ? [{ id: "existing", name: "meta_image", previewUrl: metaImage }] : []}
                      onChange={(files) => setFileValue("meta_image", files[0] ?? null)}
                      labels={{ browseText: t("upload.browse"), dragText: t("upload.hint"), maxSizeText: t("upload.imageFormat") }}
                      useGlobalSettings={false}
                    />
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>
        </div>

        {/* ── Sidebar ── */}
        <div className="flex min-w-0 flex-col gap-6">

          {/* Main image */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("sections.mainImage")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-4">
              <p className="text-xs text-muted-foreground">{t("upload.maxImageSize")}</p>
              <FormField
                control={form.control}
                name="featured_image"
                render={() => (
                  <FormItem>
                    <UnifiedFileUploader
                      multiple={false}
                      accept="image/*"
                      previewVariant="grid"
                      value={featuredImage instanceof File ? [featuredImage] : []}
                      externalPreviewItems={typeof featuredImage === "string" ? [{ id: "existing", name: "featured_image", previewUrl: featuredImage }] : []}
                      onChange={(files) => setFileValue("featured_image", files[0] ?? null)}
                      labels={{ browseText: t("upload.browse"), dragText: t("upload.hint"), maxSizeText: t("upload.imageFormat") }}
                      useGlobalSettings={false}
                    />
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="image_alt"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">{t("fields.imageAlt")}</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder={t("placeholders.imageAlt")} className="h-11 rounded-xl border-border" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* Classification */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("sections.classification")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-4">
              <FormField
                control={form.control}
                name="category_id"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("fields.category")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <Select
                      value={field.value != null ? String(field.value) : ""}
                      onValueChange={(v) => field.onChange(v ? Number(v) : null)}
                    >
                      <FormControl>
                        <SelectTrigger className="h-11 rounded-xl">
                          <SelectValue placeholder={t("placeholders.category")} />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {categories.map((cat) => (
                          <SelectItem key={cat.id} value={String(cat.id)}>
                            {cat.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="status"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("fields.status")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <FormControl>
                        <SelectTrigger className="h-11 rounded-xl">
                          <SelectValue placeholder={t("placeholders.status")} />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {STATUS_VALUES.map((status) => (
                          <SelectItem key={status} value={status}>
                            {t(`statuses.${status}`)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* Publish */}
          <Card className="rounded-2xl border border-border shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">{t("fields.publishMode")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-4">
              <FormField
                control={form.control}
                name="publish_type"
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <RadioGroup
                        value={field.value}
                        onValueChange={field.onChange}
                        className="flex flex-col gap-3"
                      >
                        <label className="flex cursor-pointer items-center gap-2">
                          <RadioGroupItem value="immediate" />
                          <span className="text-sm text-foreground">{t("publishModes.instant")}</span>
                        </label>
                        <label className="flex cursor-pointer items-center gap-2">
                          <RadioGroupItem value="scheduled" />
                          <span className="text-sm text-foreground">{t("publishModes.schedule")}</span>
                        </label>
                      </RadioGroup>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {publishType === "scheduled" && (
                <FormField
                  control={form.control}
                  name="published_at"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm text-foreground">{t("fields.publishDate")}</FormLabel>
                      <FormControl>
                        <Input
                          type="datetime-local"
                          value={field.value ?? ""}
                          onChange={(e) => field.onChange(e.target.value || null)}
                          className="h-11 rounded-xl border-border"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              <div className="flex gap-3 pt-1">
                <Button
                  type="button"
                  variant="outline"
                  className="h-11 flex-1 rounded-xl border-primary text-primary hover:bg-primary/5"
                  onClick={onSaveDraft}
                  disabled={isSubmitting}
                >
                  {t("actions.saveDraft")}
                </Button>
                <Button
                  type="submit"
                  className="h-11 flex-1 rounded-xl"
                  disabled={isSubmitting}
                >
                  {isSubmitting && <Loader2 className="me-1 size-4 animate-spin" />}
                  {mode === "create" ? t("actions.publish") : t("actions.saveChanges")}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </form>
    </Form>
  );
}
