import z from "zod";
import { api } from "~/utils/api";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { CarouselAnnuncio } from "~/components/annuncio_card";
import { zAnnuncioId } from "~/server/utils/zod_types";
import toast from "react-hot-toast";
import type { Annunci } from "~/schemas/public/Annunci";
import { DualInputLayout } from "~/components/custom_ui/inputLayouts";
import { PhoneInput } from "~/components/phone-input";
import type { Caratteristiche } from "~/utils/kanel-types";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "~/components/ui/popover";
import { format } from "date-fns";
import { Calendar } from "~/components/ui/calendar";
import { it } from "date-fns/locale";
import {
  MultiSelect,
  type ListOption,
} from "~/components/custom_ui/multiselect";
import { Switch } from "~/components/ui/switch";
import { filteredCaratteristiche } from "~/hooks/schedaAnnuncioUtils";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import Input from "~/components/custom_ui/input";
import { Textarea } from "~/components/custom_ui/textarea";
import { CalendarIcon, Eye, RotateCw } from "lucide-react";
import Link from "next/link";
import { StatusBadge } from "~/pages/area-riservata/admin/edit-annuncio/[id]";
import { cn } from "~/lib/utils";

export const AnnuncioEditForm = ({ data }: { data: Annunci }) => {
  const schema = z.object({
    //BASE
    id: zAnnuncioId,
    titolo_it: z.string().nullable(),
    desc_it: z.string().nullable(),
    titolo_en: z.string().nullable(),
    desc_en: z.string().nullable(),
    stato: z.string().nullable(),
    web: z.boolean().nullable(),
    homepage: z.boolean().nullable(),
    codice: z.string(),

    // DATI LOCATORE
    locatore: z.string().nullable(),
    email: z.email().optional(),
    numero: z.string().nullable(),

    // DATI IMMOBILE
    indirizzo: z.string().nullable(),
    civico: z.string().nullable(),
    comune: z.string().nullable(),
    cap: z.string().nullable(),
    provincia: z.string().nullable(),
    regione: z.string().nullable(),
    lat: z.string().nullable(),
    lon: z.string().nullable(),
    indirizzo_secondario: z.string().nullable(),
    civico_secondario: z.string().nullable(),
    lat_secondario: z.string().nullable(),
    lon_secondario: z.string().nullable(),

    // DATI CONTRATTO
    tipo: z.string().nullable(),
    categorie: z.string().array().nullable(),
    prezzo: z.number(),
    disponibile_da: z.date().nullable(),
    consegna: z.number().nullable(),
    persone: z.string().array().nullable(),
    permanenza: z.number().array().nullable(),

    // ALTRI DATI IMMOBILE
    anno: z.string().nullable(),
    classe: z.string().nullable(),
    mq: z.string().nullable(),
    piano: z.string().nullable(),
    piano_palazzo: z.number().nullable(),
    unita_condominio: z.number().nullable(),
    numero_vani: z.number().nullable(),
    numero_camere: z.number().nullable(),
    numero_bagni: z.number().nullable(),
    numero_balconi: z.number().nullable(),
    numero_terrazzi: z.number().nullable(),
    numero_box: z.number().nullable(),
    numero_postiauto: z.number().nullable(),
    accessori: z.string().array().nullable(),
    caratteristiche: z.custom<Caratteristiche>().nullable(),

    // MEDIA
    //url_immagini: z.string().array().nullable(),
    //url_video: z.string().array().nullable(),
    //og_url: z.string().nullable(),

    //creato_il: z.date().nullable(),
    //modificato_il: z.date().nullable(),
  });

  type FormValues = z.infer<typeof schema>;
  const { locale } = useTranslation();
  const utils = api.useUtils();

  const { mutate: edit } = api.annunci.editAnnuncio.useMutation({
    onSettled: async () => {
      await utils.annunci.getAnnuncio.invalidate({ cod: data.codice });
      await utils.annunci.getAnnuncioByIdForEdit.invalidate({ id: data.id });
      await utils.annunci.getAnnunciList.invalidate();
      toast.success("Annuncio modificato con successo");
    },
  });

  const defaultValues: FormValues = {
    ...data,
    email: data.email || undefined,
  };

  z.config(z.locales[locale]());

  const form = useZodForm(schema, {
    defaultValues: defaultValues,
  });

  function onSubmit(fields: FormValues) {
    edit({
      annuncioId: data.id,
      data: { ...fields, email: fields.email || null },
    });
  }

  const personeOptions: ListOption[] = [
    "single",
    "coppia",
    "colleghi",
    "famiglia",
  ].map((p) => ({
    value: p,
    label: p,
  }));

  const permanenzaOptions: ListOption[] = [
    { value: "1", label: "1 mese" },
    { value: "3", label: "3 mesi" },
    { value: "6", label: "6 mesi" },
    { value: "9", label: "9 mesi" },
    { value: "12", label: "12 mesi" },
    { value: "18", label: "18 mesi" },
    { value: "24", label: "24 mesi" },
  ];
  const tipoOptions: ListOption[] = [
    "Transitorio",
    "Stabile",
    "Vendita",
    "Cessione",
    "Errore",
  ].map((o) => ({ value: o, label: o }));

  const statoOptions = ["Attivo", "Sospeso", "Trattativa"].map((o) => ({
    value: o,
    label: o,
  }));

  const consegnaOptions: ListOption[] = [
    { value: "1", label: "Gennaio" },
    { value: "2", label: "Febbraio" },
    { value: "3", label: "Marzo" },
    { value: "4", label: "Aprile" },
    { value: "5", label: "Maggio" },
    { value: "6", label: "Giugno" },
    { value: "7", label: "Luglio" },
    { value: "8", label: "Agosto" },
    { value: "9", label: "Settembre" },
    { value: "10", label: "Ottobre" },
    { value: "11", label: "Novembre" },
    { value: "12", label: "Dicembre" },
  ];
  return (
    <>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="mt-3 grid flex-1 items-start gap-4 p-2 sm:px-4 sm:py-0 md:gap-8"
        >
          <div className="mx-auto grid w-full max-w-7xl flex-1 auto-rows-max gap-4">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-2xl font-semibold tracking-tight whitespace-nowrap">
                Annuncio {data.codice}
              </h1>
              <StatusBadge status={data.stato} />
              <Link href={`/annuncio/${data.codice}`} target="_blank">
                <Button
                  variant="outline"
                  size="sm"
                  className="flex items-center gap-2"
                >
                  <Eye /> pubblica
                </Button>
              </Link>

              <div className="hidden items-center gap-2 md:ml-auto md:flex">
                <Button variant="outline" size="sm">
                  Annulla
                </Button>
                <Button size="sm" className="bg-green-500">
                  Salva
                </Button>
              </div>
            </div>
            <div className="grid h-max gap-3 md:grid-cols-[1fr_250px] lg:grid-cols-3">
              <div className="h-full items-start gap-3 lg:col-span-2">
                <Card className="h-full py-4">
                  <CardContent className="h-full w-full grow px-4">
                    <Tabs defaultValue="ita">
                      <TabsList className="grid h-full w-full grid-cols-2">
                        <TabsTrigger value="ita">Italiano</TabsTrigger>
                        <TabsTrigger value="eng">Inglese</TabsTrigger>
                      </TabsList>
                      <TabsContent value="ita">
                        <Card>
                          <CardHeader>
                            <CardTitle>Descrizione ITA</CardTitle>
                          </CardHeader>
                          <CardContent>
                            <div className="grid gap-6">
                              <div className="grid gap-3">
                                <FormField
                                  control={form.control}
                                  name="titolo_it"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex flex-wrap items-center gap-x-2">
                                        <FormLabel htmlFor="titolo_it">
                                          Titolo ITA
                                        </FormLabel>
                                        <FormMessage />
                                      </div>

                                      <FormControl>
                                        <Input
                                          placeholder=""
                                          {...field}
                                          id="titolo_it"
                                          value={field.value || undefined}
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </div>
                              <div className="grid gap-3">
                                <FormField
                                  control={form.control}
                                  name="desc_it"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex flex-wrap items-center gap-x-2">
                                        <FormLabel htmlFor="desc_it">
                                          Descrizione ITA
                                        </FormLabel>
                                        <FormMessage />
                                      </div>

                                      <FormControl>
                                        <Textarea
                                          placeholder=""
                                          className="min-h-64"
                                          {...field}
                                          id="desc_it"
                                          value={field.value || undefined}
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </TabsContent>
                      <TabsContent value="eng">
                        <Card>
                          <CardHeader>
                            <CardTitle>Descrizione ENG</CardTitle>
                          </CardHeader>
                          <CardContent>
                            <div className="grid gap-6">
                              <div className="grid gap-3">
                                <FormField
                                  control={form.control}
                                  name="titolo_en"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex flex-wrap items-center gap-x-2">
                                        <FormLabel htmlFor="titolo_en">
                                          Titolo ENG
                                        </FormLabel>
                                        <FormMessage />
                                      </div>

                                      <FormControl>
                                        <Input
                                          placeholder=""
                                          {...field}
                                          id="titolo_en"
                                          value={field.value || undefined}
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </div>
                              <div className="grid gap-3">
                                <FormField
                                  control={form.control}
                                  name="desc_en"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex flex-wrap items-center gap-x-2">
                                        <FormLabel htmlFor="desc_en">
                                          Descrizione ENG
                                        </FormLabel>
                                        <FormMessage />
                                      </div>

                                      <FormControl>
                                        <Textarea
                                          placeholder=""
                                          className="min-h-64"
                                          {...field}
                                          id="desc_en"
                                          value={field.value || undefined}
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </TabsContent>
                    </Tabs>
                  </CardContent>
                </Card>
              </div>
              <div className="grid auto-rows-max items-start gap-3 lg:gap-8">
                <Card>
                  <CardHeader>
                    <CardTitle>Status Annuncio</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <FormField
                      control={form.control}
                      name="stato"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="select-stato">Stato</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <MultiSelect
                              elementId="select-stato"
                              elementName="stato"
                              options={statoOptions}
                              defaultValue={
                                field.value
                                  ? statoOptions.filter((o) =>
                                      field.value?.includes(o.value),
                                    )
                                  : undefined
                              }
                              onValueChange={async (value) => {
                                field.onChange(value.value);
                              }}
                              placeholder="Seleziona..."
                              isMulti={false}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="web"
                      render={({ field }) => (
                        <FormItem className="mt-6 w-full px-4">
                          <div className="flex w-full items-center justify-between gap-x-4">
                            <FormLabel htmlFor="web">Web</FormLabel>
                            <FormControl>
                              <Switch
                                checked={field.value || false}
                                onCheckedChange={field.onChange}
                                id="web"
                                className="data-[state=checked]:bg-neutral-700"
                              />
                            </FormControl>
                            <FormMessage />
                          </div>
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="homepage"
                      render={({ field }) => (
                        <FormItem className="mt-6 w-full px-4">
                          <div className="flex items-center justify-between gap-x-4">
                            <FormLabel htmlFor="homepage">Homepage</FormLabel>
                            <FormControl>
                              <Switch
                                checked={field.value || false}
                                onCheckedChange={field.onChange}
                                id="homepage"
                                className="data-[state=checked]:bg-neutral-700"
                              />
                            </FormControl>
                            <FormMessage />
                          </div>
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>
                <Card className="overflow-hidden">
                  <CardHeader>
                    <CardTitle>Imagini Annuncio</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {data.url_immagini && data.url_immagini.length > 0 ? (
                      <CarouselAnnuncio
                        single
                        immagini={data.url_immagini.map(
                          (v) => `/go-api/images/get/${v}`,
                        )}
                      />
                    ) : (
                      <div className="text-center text-gray-500">
                        Nessuna immagine disponibile
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            </div>
            <Card>
              <CardHeader>
                <CardTitle>Dati di contatto</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <FormField
                  control={form.control}
                  name="locatore"
                  render={({ field }) => (
                    <FormItem>
                      <div className="flex flex-wrap items-center gap-x-2">
                        <FormLabel htmlFor="locatore">
                          Locatore o incaricato
                        </FormLabel>
                        <FormMessage />
                      </div>

                      <FormControl>
                        <Input
                          placeholder=""
                          {...field}
                          id="locatore"
                          value={field.value || undefined}
                          onChange={(e) =>
                            field.onChange(e.target.value || null)
                          }
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="email">Email</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder="esempio@email.com"
                              {...field}
                              id="email"
                              value={field.value || undefined}
                              onChange={(e) =>
                                field.onChange(
                                  e.target.value && e.target.value !== ""
                                    ? e.target.value
                                    : null,
                                )
                              }
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="numero"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="numero">Telefono</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <PhoneInput
                              {...field}
                              id="numero"
                              value={field.value || undefined}
                              onChange={(n) => field.onChange(n || null)}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />

                <p>
                  Indirizo: {data.indirizzo}, {data.civico} {data.comune} (
                  {data.provincia})
                </p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Dati Immobile</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="indirizzo"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="indirizzo">Indirizzo</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="indirizzo"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="civico"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="civico">Civico</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="civico"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="comune"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="comune">Comune</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="comune"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="cap"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="cap">Cap</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="cap"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="provincia"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="provincia">Provincia</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="provincia"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="regione"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="regione">Regione</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="regione"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="lat"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="lat">Lat</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="lat"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="lon"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="lon">Lon</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="lon"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <p>
                  <Link
                    href={`https://www.google.com/maps/place/${form.getValues("lat")},${form.getValues("lon")}`}
                    target="_blank"
                  >
                    🗺️ <span className="underline">Vedi su maps</span>
                  </Link>
                </p>

                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="indirizzo_secondario"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="indirizzo_secondario">
                              Indirizzo Secondario
                            </FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="indirizzo_secondario"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="civico_secondario"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="civico_secondario">
                              Civico Secondario
                            </FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="civico_secondario"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="lat_secondario"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="lat_secondario">
                              Lat Secondario
                            </FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="lat_secondario"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="lon_secondario"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="lon_secondario">
                              Lon Secondario
                            </FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              placeholder=""
                              {...field}
                              id="lon_secondario"
                              value={field.value || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <p>
                  <Link
                    href={`https://www.google.com/maps/place/${form.getValues("lat_secondario")},${form.getValues("lon_secondario")}`}
                    target="_blank"
                  >
                    🗺️ <span className="underline">Vedi su maps</span>
                  </Link>
                </p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Dati Annuncio</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="tipo"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="select-tipo">
                              Tipo annuncio
                            </FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <MultiSelect
                              elementId="select-tipo"
                              elementName="tipo"
                              options={tipoOptions}
                              defaultValue={
                                field.value
                                  ? tipoOptions.filter((o) =>
                                      field.value?.includes(o.value),
                                    )
                                  : undefined
                              }
                              onValueChange={async (value) => {
                                field.onChange(value.value);
                              }}
                              placeholder="Seleziona..."
                              isMulti={false}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="categorie"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="categorie">Categorie</FormLabel>
                            <FormMessage />
                          </div>

                          <p className="h-[42px]" id="categorie">
                            {field.value?.join(", ")}
                          </p>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="prezzo"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="prezzo">Prezzo</FormLabel>{" "}
                            <FormMessage />
                          </div>

                          <FormControl>
                            <Input
                              type="number"
                              step="0.01"
                              placeholder=""
                              {...field}
                              id="prezzo"
                              onChange={(e) =>
                                e.target.value === ""
                                  ? field.onChange(null)
                                  : field.onChange(
                                      parseFloat(e.target.value) * 100,
                                    )
                              }
                              value={field.value / 100 || undefined}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="disponibile_da"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="disponibile_da">
                              Disponibile Da
                            </FormLabel>
                            <FormMessage />
                          </div>
                          <Popover>
                            <PopoverTrigger asChild>
                              <FormControl>
                                <Button
                                  variant={"outline"}
                                  id="disponibile_da"
                                  className={cn(
                                    "h-[42px] w-full pl-3 text-left font-medium",
                                    !field.value && "text-muted-foreground",
                                    `text-primary dark:bg-primary rounded-lg border border-neutral-300 bg-white shadow-xs outline-hidden file:border-0 file:bg-transparent file:text-sm file:font-medium hover:border-neutral-400 focus:border-neutral-400 disabled:cursor-not-allowed disabled:opacity-50 aria-expanded:border-neutral-400 dark:border-neutral-500 dark:text-white dark:placeholder:text-neutral-400 dark:hover:border-neutral-400 dark:focus:border-transparent dark:aria-expanded:border-neutral-400`,
                                  )}
                                >
                                  {field.value ? (
                                    format(field.value, "PPP", {
                                      locale: it,
                                    })
                                  ) : (
                                    <span>Scegli</span>
                                  )}
                                  <CalendarIcon className="ml-auto size-4 opacity-50" />
                                </Button>
                              </FormControl>
                            </PopoverTrigger>
                            <PopoverContent
                              className="w-auto p-0"
                              align="start"
                            >
                              <Calendar
                                locale={it}
                                mode="single"
                                defaultMonth={field.value || undefined}
                                captionLayout="dropdown"
                                selected={field.value || undefined}
                                onSelect={field.onChange}
                                // eslint-disable-next-line jsx-a11y/no-autofocus
                                autoFocus
                              />
                            </PopoverContent>
                          </Popover>
                        </FormItem>
                      )}
                    />
                  }
                />
                <DualInputLayout
                  children1={
                    <FormField
                      control={form.control}
                      name="consegna"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="select-consegna">
                              Consegna
                            </FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <MultiSelect
                              elementId="select-consegna"
                              elementName="consegna"
                              options={consegnaOptions}
                              defaultValue={
                                field.value
                                  ? consegnaOptions.filter((o) =>
                                      field.value?.toString().includes(o.value),
                                    )
                                  : undefined
                              }
                              onValueChange={async (value) => {
                                field.onChange(parseInt(value.value));
                              }}
                              placeholder="Seleziona..."
                              isMulti={false}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                  children2={
                    <FormField
                      control={form.control}
                      name="persone"
                      render={({ field }) => (
                        <FormItem>
                          <div className="flex flex-wrap items-center gap-x-2">
                            <FormLabel htmlFor="select-pers">Persone</FormLabel>
                            <FormMessage />
                          </div>

                          <FormControl>
                            <MultiSelect
                              elementId="select-pers"
                              elementName="persone"
                              options={personeOptions}
                              defaultValue={
                                field.value
                                  ? personeOptions.filter((o) =>
                                      field.value?.includes(o.value),
                                    )
                                  : undefined
                              }
                              onValueChange={async (value) => {
                                field.onChange(value.map((v) => v.value));
                              }}
                              placeholder="Seleziona..."
                              isMulti={true}
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />
                <FormField
                  control={form.control}
                  name="permanenza"
                  render={({ field }) => (
                    <FormItem>
                      <div className="flex flex-wrap items-center gap-x-2">
                        <FormLabel htmlFor="select-perm">Permanenza</FormLabel>
                        <FormMessage />
                      </div>

                      <FormControl>
                        <MultiSelect
                          elementId="select-perm"
                          elementName="permanenza"
                          options={permanenzaOptions}
                          defaultValue={
                            field.value
                              ? permanenzaOptions.filter((o) =>
                                  field.value?.includes(parseInt(o.value)),
                                )
                              : undefined
                          }
                          onValueChange={async (value) => {
                            field.onChange(value.map((v) => parseInt(v.value)));
                          }}
                          placeholder="Seleziona..."
                          isMulti={true}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Altri Dati Immobile</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex w-full flex-col flex-wrap items-start justify-between gap-4 sm:flex-row">
                  <FormField
                    control={form.control}
                    name="anno"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="anno">Anno costruzione</FormLabel>{" "}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            {...field}
                            id="anno"
                            value={field.value || undefined}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value != "" ? e.target.value : null,
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="classe"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="classe">Classe</FormLabel>{" "}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            {...field}
                            id="classe"
                            value={field.value || undefined}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value != "" ? e.target.value : null,
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="mq"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="mq">Metri Quadri</FormLabel>{" "}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            {...field}
                            id="mq"
                            value={field.value || undefined}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value != "" ? e.target.value : null,
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="piano"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="piano">Piano</FormLabel>{" "}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            {...field}
                            id="piano"
                            value={field.value || undefined}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value != "" ? e.target.value : null,
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="piano_palazzo"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="piano_palazzo">
                            Piani Palazzo
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("piano_palazzo", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="piano_palazzo"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="unita_condominio"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="unita_condominio">
                            Unità Condominio
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("unita_condominio", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="unita_condominio"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="numero_vani"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_vani">
                            Numero Vani
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_vani", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_vani"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="numero_camere"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_camere">
                            Numero Camere
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_camere", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_camere"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero_bagni"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_bagni">
                            Numero Bagni
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_bagni", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_bagni"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero_balconi"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_balconi">
                            Numero Balconi
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_balconi", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_balconi"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero_terrazzi"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_terrazzi">
                            Numero Terrazzi
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_terrazzi", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_terrazzi"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero_box"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_box">
                            Numero Box Auto
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_box", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_box"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="numero_postiauto"
                    render={({ field }) => (
                      <FormItem>
                        <div className="relative flex flex-wrap items-center gap-x-2">
                          <FormLabel htmlFor="numero_postiauto">
                            Numero Posti Auto
                          </FormLabel>
                          {field.value !== null && field.value != 0 && (
                            <Button
                              type="button"
                              size="sm"
                              variant="link"
                              onClick={() => {
                                form.setValue("numero_postiauto", null);
                              }}
                              className="absolute -top-2 right-0 flex items-center gap-1"
                            >
                              <RotateCw className="size-4" />
                              Reset
                            </Button>
                          )}
                          <FormMessage />
                        </div>

                        <FormControl>
                          <Input
                            placeholder=""
                            type="number"
                            {...field}
                            id="numero_postiauto"
                            value={field.value || 0}
                            onChange={(e) =>
                              field.onChange(
                                e.target.value === "0" || e.target.value === ""
                                  ? null
                                  : parseInt(e.target.value),
                              )
                            }
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="accessori"
                  render={({ field }) => (
                    <FormItem>
                      <div className="flex flex-wrap items-center gap-x-2">
                        <FormLabel htmlFor="accessori">Accessori</FormLabel>
                        <FormMessage />
                      </div>

                      <FormControl>
                        <p className="h-[42px]" id="accessori">
                          {field.value?.join(", ")}
                        </p>
                      </FormControl>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="caratteristiche"
                  render={({ field }) => (
                    <FormItem>
                      <div className="flex flex-wrap items-center gap-x-2">
                        <FormLabel htmlFor="caratteristiche">
                          Caratteristiche
                        </FormLabel>
                        <FormMessage />
                      </div>

                      <FormControl>
                        <p className="h-[42px]" id="caratteristiche">
                          {field.value
                            ? filteredCaratteristiche(field.value)
                                .map((v) => v.text)
                                .join(", ")
                            : ""}
                        </p>
                      </FormControl>
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Media</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex w-full flex-col items-start justify-between gap-4 sm:flex-row"></div>
              </CardContent>
            </Card>
          </div>
        </form>
      </Form>
    </>
  );
};
