import { Eye } from "lucide-react";
import type { GetServerSideProps } from "next";
import Link from "next/link";
import { AreaRiservataLayout } from "~/components/Layout";
import Input from "~/components/custom_ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select";
import { Textarea } from "~/components/custom_ui/textarea";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { Badge } from "~/components/ui/badge";
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 { cn } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";
import { z } from "zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { customErrorMapWrapper } from "~/hooks/locale";
import { CarouselAnnuncio } from "~/components/annuncio_card";
import { zAnnuncioId } from "~/server/utils/zod_types";
import toast from "react-hot-toast";
import type { AnnunciWithCoverImage } from "~/server/controllers/annunci.controller";
import type { AnnunciId } from "~/schemas/public/Annunci";
import { DualInputLayout } from "~/components/custom_ui/inputLayouts";
import { PhoneInput } from "~/components/phone-input";

type AnnuncioEditProps = {
  id: AnnunciId;
};

const AnnuncioEdit: NextPageWithLayout<AnnuncioEditProps> = ({
  id,
}: AnnuncioEditProps) => {
  const { data, isLoading } = api.annunci.getAnnuncioById.useQuery(
    {
      id,
    },
    { refetchOnMount: false },
  );

  if (isLoading) return <LoadingPage />;
  if (!data) {
    return <Status500 />;
  }

  return (
    <>
      <AnnuncioEditForm data={data} />
    </>
  );
};

const AnnuncioEditForm = ({ data }: { data: AnnunciWithCoverImage }) => {
  const EdiAnnuncioSchema = z.object({
    annuncioId: zAnnuncioId,
    titolo_it: z.string().nonempty("Inserisci un titolo valido"),
    desc_it: z.string().nonempty("Inserisci una descrizione valida"),
    titolo_en: z.string().nonempty("Inserisci un titolo valido"),
    desc_en: z.string().nonempty("Inserisci una descrizione valida"),
    status: z.string().nonempty("Seleziona uno stato"),
    locatore: z.string().nonempty("Inserisci il locatore"),
    email: z.string().email("Inserisci un'email valida"),
    numero: z.string().nonempty("Inserisci un numero di telefono"),
  });

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

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

  const defaultValues: EditAnnuncioFormValues = {
    annuncioId: data.id,
    titolo_it: data.titolo_it || "",
    desc_it: data.desc_it || "",
    titolo_en: data.titolo_en || "",
    desc_en: data.desc_en || "",
    status: data.stato || "",
    locatore: data.locatore || "",
    email: data.email || "",
    numero: data.numero || "",
  };

  z.setErrorMap(customErrorMapWrapper(locale));

  const form = useZodForm({
    schema: EdiAnnuncioSchema,
    defaultValues: defaultValues,
  });
  function onSubmit(fields: EditAnnuncioFormValues) {
    edit(fields);
  }

  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-4 md:grid-cols-[1fr_250px] lg:grid-cols-3 lg:gap-8">
              <div className="h-full items-start gap-4 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"
                                        />
                                      </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"
                                        />
                                      </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"
                                        />
                                      </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"
                                        />
                                      </FormControl>
                                    </FormItem>
                                  )}
                                />
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </TabsContent>
                    </Tabs>
                  </CardContent>
                </Card>
              </div>
              <div className="grid auto-rows-max items-start gap-4 lg:gap-8">
                <Card>
                  <CardHeader>
                    <CardTitle>Status Annuncio</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid gap-6">
                      <div className="grid gap-3">
                        <FormField
                          control={form.control}
                          name="status"
                          render={({ field }) => (
                            <FormItem>
                              <div className="flex flex-wrap items-center gap-x-2">
                                <FormMessage />
                              </div>

                              <FormControl>
                                <Select
                                  value={field.value}
                                  onValueChange={field.onChange}
                                >
                                  <SelectTrigger id="status">
                                    <SelectValue placeholder="Select status" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="Attivo">
                                      Attivo
                                    </SelectItem>
                                    <SelectItem value="Sospeso">
                                      Sospeso
                                    </SelectItem>
                                    <SelectItem value="Trattativa">
                                      Trattativa
                                    </SelectItem>
                                  </SelectContent>
                                </Select>
                              </FormControl>
                            </FormItem>
                          )}
                        />
                      </div>
                    </div>
                  </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} />
                    ) : (
                      <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" />
                      </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"
                            />
                          </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" />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  }
                />

                <p>
                  Indirizo: {data.indirizzo}, {data.civico} {data.comune} (
                  {data.provincia})
                </p>
              </CardContent>
            </Card>
          </div>
        </form>
      </Form>
    </>
  );
};

export const getServerSideProps = (async (context) => {
  const annuncioId = context.params?.id && parseInt(String(context.params.id));

  const check = zAnnuncioId.safeParse(annuncioId);
  if (!check.success) {
    return {
      redirect: {
        destination: "/500",
        permanent: false,
      },
    };
  }

  const ssg = generateSSGHelper();

  await ssg.annunci.getAnnuncioById.prefetch({ id: check.data });

  return {
    props: {
      trpcState: ssg.dehydrate(),
      id: check.data,
    },
  };
}) satisfies GetServerSideProps<AnnuncioEditProps>;

export default AnnuncioEdit;

AnnuncioEdit.getLayout = function getLayout(page) {
  return <AreaRiservataLayout>{page}</AreaRiservataLayout>;
};

export const StatusBadge = ({ status }: { status: string | null }) => {
  let colore = "";
  switch (status) {
    case "Sospeso":
      colore = "bg-yellow-500 border-yellow-500 text-white";
      break;
    case "Trattativa":
      colore = "bg-purple-500 border-purple-500 text-white";
      break;
    case "Attivo":
      colore = "bg-green-500 border-green-500 text-white";
      break;
    case null:
    default:
      colore = "bg-neutral-500 border-neutral-500 text-white";
      break;
  }

  return (
    <Badge variant="outline" className={cn("", colore)}>
      {status}
    </Badge>
  );
};
