"use client";

import { PageContentEditor } from "@/components/dashboard/pages/page-content-editor";
import type { PreviousWorkUpsertFormValues } from "@/components/dashboard/previous-work/previous-work-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 { UnifiedFileUploader } from "@/components/shared/unified-file-uploader";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useLocale, useTranslations } from "next-intl";
import type { SubmitHandler, UseFormReturn } from "react-hook-form";

interface PreviousWorkFormViewProps {
  form: UseFormReturn<PreviousWorkUpsertFormValues>;
  formId: string;
  mode: "create" | "edit";
  serviceOptions: Array<{ id: number; label: string }>;
  currentImagePath?: string;
  onSubmit: SubmitHandler<PreviousWorkUpsertFormValues>;
  isSubmitting: boolean;
}

export function PreviousWorkFormView({
  form,
  formId,
  mode,
  serviceOptions,
  currentImagePath,
  onSubmit,
  isSubmitting,
}: PreviousWorkFormViewProps) {
  const t = useTranslations("dashboard.previousWork");
  const locale = useLocale();
  const isRtl = locale === "ar";
  const image = form.watch("image");
  const gallery = form.watch("gallery");
  const requiredMessage = t("form.validation.required");

  return (
    <Form {...form}>
      <form
        id={formId}
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-1 gap-6 [direction:ltr] xl:grid-cols-[316px_minmax(0,1fr)]"
      >
        <Card
          dir={isRtl ? "rtl" : "ltr"}
          className="order-1 h-fit rounded-2xl border border-border bg-card shadow-none"
        >
          <CardHeader className="border-b border-border py-4">
            <CardTitle className="text-base font-bold text-foreground">
              {t("form.sections.mainImage")}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4 p-4">
            <FormField
              control={form.control}
              name="image"
              rules={{
                validate: (file: File | null) => {
                  if (!file) {
                    return mode === "edit" || requiredMessage;
                  }
                  if (!["image/png", "image/jpeg", "image/jpg", "image/svg+xml"].includes(file.type)) {
                    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>
                  <UnifiedFileUploader
                    multiple={false}
                    accept="image/png,image/jpeg,image/jpg,image/svg+xml"
                    previewVariant="grid"
                    value={image ? [image] : []}
                    externalPreviewItems={mode === "edit" && currentImagePath && !image ? [{ id: "existing", name: "image", previewUrl: currentImagePath }] : []}
                    onChange={(files) => form.setValue("image", files[0] ?? null, { shouldDirty: true, shouldTouch: true, shouldValidate: true })}
                    disabled={isSubmitting}
                    labels={{ browseText: t("form.upload.browse"), dragText: t("form.upload.hint"), maxSizeText: t("form.upload.helper") }}
                    useGlobalSettings={false}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
          </CardContent>
        </Card>

        <div dir={isRtl ? "rtl" : "ltr"} className="order-2 min-w-0 space-y-6">
          <Card className="rounded-2xl border border-border bg-card shadow-none">
            <CardContent className="space-y-5 p-6">
              <div className="grid gap-5 lg:grid-cols-2">
                <FormField
                  control={form.control}
                  name="service_id"
                  rules={{
                    validate: (value) => (value > 0 ? true : requiredMessage),
                  }}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm text-foreground">
                        {t("form.fields.service")} <span className="text-destructive">*</span>
                      </FormLabel>
                      <Select value={field.value ? String(field.value) : ""} onValueChange={(value) => field.onChange(Number(value))}>
                        <FormControl>
                          <SelectTrigger className="h-12 rounded-xl border-border">
                            <SelectValue placeholder={t("form.placeholders.service")} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {serviceOptions.map((service) => (
                            <SelectItem key={service.id} value={String(service.id)}>
                              {service.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

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

              <div className="grid gap-5 lg:grid-cols-2">
                <FormField
                  control={form.control}
                  name="order"
                  rules={{ 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}
                          value={field.value}
                          onChange={(event) => field.onChange(event.target.valueAsNumber)}
                          disabled={isSubmitting}
                          className="h-12 rounded-xl border-border"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="is_featured"
                  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.featured")}
                      </FormLabel>
                      <FormControl>
                        <Switch checked={field.value} onCheckedChange={field.onChange} disabled={isSubmitting} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </div>

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

          <Card className="rounded-2xl border border-border bg-card shadow-none">
            <CardHeader className="border-b border-border py-4">
              <CardTitle className="text-base font-bold text-foreground">
                {t("form.sections.gallery")}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-6">
              <FormField
                control={form.control}
                name="gallery"
                render={() => (
                  <FormItem>
                    <UnifiedFileUploader
                      multiple={true}
                      accept="image/png,image/jpeg,image/jpg,image/svg+xml"
                      previewVariant="grid"
                      value={gallery}
                      onChange={(files) => form.setValue("gallery", files, { shouldDirty: true, shouldTouch: true, shouldValidate: true })}
                      disabled={isSubmitting}
                      labels={{ browseText: t("form.gallery.add"), dragText: t("form.upload.hint"), maxSizeText: t("form.gallery.empty") }}
                      useGlobalSettings={false}
                    />
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>
        </div>
      </form>
    </Form>
  );
}
