"use client";

import { PageContentEditor } from "@/components/dashboard/pages/page-content-editor";
import type { ServiceUpsertFormValues } from "@/components/dashboard/services/services-types";
import { Card, CardContent } 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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useTranslations } from "next-intl";
import type { SubmitHandler, UseFormReturn } from "react-hook-form";

interface ServiceUpsertFormViewProps {
  form: UseFormReturn<ServiceUpsertFormValues>;
  formId: string;
  mode: "create" | "edit";
  currentImagePath?: string;
  onSubmit: SubmitHandler<ServiceUpsertFormValues>;
  isSubmitting: boolean;
}

export function ServiceUpsertFormView({
  form,
  formId,
  mode,
  currentImagePath,
  onSubmit,
  isSubmitting,
}: ServiceUpsertFormViewProps) {
  const t = useTranslations("dashboard.services");
  const requiredMessage = t("form.validation.required");

  const image = form.watch("image");

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

  return (
    <Form {...form}>
      <form
        id={formId}
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_316px]"
      >
        <div className="min-w-0 space-y-6">
          <Card className="rounded-2xl border border-border bg-card 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("form.fields.title")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder={t("form.placeholders.title")}
                        disabled={isSubmitting}
                        className="h-12 rounded-xl border-border"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

              <FormField
                control={form.control}
                name="description"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("form.fields.description")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <FormControl>
                      <PageContentEditor
                        value={field.value || ""}
                        onChange={field.onChange}
                        placeholder={t("form.placeholders.description")}
                      />
                    </FormControl>
                    <FormMessage className="mt-2" />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="icon"
                rules={{ required: requiredMessage }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-sm text-foreground">
                      {t("form.fields.icon")} <span className="text-destructive">*</span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder={t("form.placeholders.icon")}
                        disabled={isSubmitting}
                        className="h-12 rounded-xl border-border"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid gap-5 lg:grid-cols-2">
                <FormField
                  control={form.control}
                  name="order"
                  rules={{ required: requiredMessage, min: { value: 0, message: requiredMessage } }}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm text-foreground">
                        {t("form.fields.order")}
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min={0}
                          disabled={isSubmitting}
                          className="h-12 rounded-xl border-border"
                          value={field.value}
                          onChange={(event) => field.onChange(event.target.valueAsNumber)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="is_active"
                  render={({ field }) => (
                    <FormItem
                      className="flex min-h-12 items-center justify-between rounded-xl border border-border px-4 py-3"
                    >
                      <FormLabel className="m-0 text-sm text-foreground">
                        {t("form.fields.active")}
                      </FormLabel>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                          disabled={isSubmitting}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </div>
            </CardContent>
          </Card>
        </div>

        <Card className="h-fit rounded-2xl border border-border bg-card shadow-none">
          <CardContent className="space-y-4 p-6">
            <FormField
              control={form.control}
              name="image"
              rules={{
                validate: (file: File | null) => {
                  if (!file) return mode === "edit" || requiredMessage;
                  if (!file.type.startsWith("image/")) return t("form.validation.image");
                  return file.size <= 5 * 1024 * 1024 || t("form.validation.imageSize");
                },
              }}
              render={() => (
                <FormItem className="space-y-3">
                  <FormLabel className="text-sm text-foreground">
                    {t("form.fields.image")}{" "}
                    {mode === "create" && <span className="text-destructive">*</span>}
                  </FormLabel>
                  {mode === "edit" && currentImagePath && !image ? (
                    <div className="text-sm text-muted-foreground">
                      {t("form.fields.currentImage")}: {currentImagePath}
                    </div>
                  ) : null}
                  <UnifiedFileUploader
                    multiple={false}
                    accept="image/*"
                    previewVariant="grid"
                    value={image ? [image] : []}
                    onChange={(files) => setFileValue("image", files[0] ?? null)}
                    disabled={isSubmitting}
                    labels={{ browseText: t("form.upload.browse"), dragText: t("form.upload.hint"), maxSizeText: t("form.upload.mediaLibrary") }}
                    useGlobalSettings={false}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
          </CardContent>
        </Card>
      </form>
    </Form>
  );
}
