"use client"

import { toast } from 'sonner';
import { useForm } from "react-hook-form";
import { z } from "zod";
import { StoreCart, StoreCartLineItem } from "@medusajs/types"
import { Form } from "@kit/ui/form";
import { Trans } from '@kit/ui/trans';
import { useTranslation } from "react-i18next";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from '@kit/ui/select';
import { updateCartPartnerLocation } from '../../_lib/server/update-cart-partner-location';

const AnalysisLocationSchema = z.object({
  locationId: z.string().min(1),
});

const MOCK_LOCATIONS: { id: string, name: string }[] = [
  { id: "synlab-tallinn-1", name: "SYNLAB - Tallinn" },
  { id: "synlab-tartu-1", name: "SYNLAB - Tartu" },
  { id: "synlab-parnu-1", name: "SYNLAB - Pärnu" },
]

export default function AnalysisLocation({ cart, analysisPackages }: { cart: StoreCart, analysisPackages: StoreCartLineItem[] }) {
  const { t } = useTranslation('cart');

  const form = useForm<z.infer<typeof AnalysisLocationSchema>>({
    defaultValues: {
      locationId: cart.metadata?.partner_location_id as string ?? '',
    },
    resolver: zodResolver(AnalysisLocationSchema),
  });

  const onSubmit = async ({ locationId }: z.infer<typeof AnalysisLocationSchema>) => {
    const promise = updateCartPartnerLocation({
      cartId: cart.id,
      lineIds: analysisPackages.map(({ id }) => id),
      partnerLocationId: locationId,
      partnerLocationName: MOCK_LOCATIONS.find((location) => location.id === locationId)?.name ?? '',
    });

    toast.promise(promise, {
      success: t(`cart:items.analysisLocation.success`),
      loading: t(`cart:items.analysisLocation.loading`),
      error: t(`cart:items.analysisLocation.error`),
    });
  }

  return (
    <div className="w-full bg-white flex flex-col txt-medium">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit((data) => onSubmit(data))}
          className="w-full mb-2 flex gap-x-2"
        >
          <Select
            value={form.watch('locationId')}
            onValueChange={(value) => {
              form.setValue('locationId', value, {
                shouldValidate: true,
                shouldDirty: true,
                shouldTouch: true,
              });

              return onSubmit(form.getValues());
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder={t('cart:locations.locationSelect')} />
            </SelectTrigger>

            <SelectContent>
              <SelectGroup>
                <SelectLabel>{t('cart:locations.locationSelect')}</SelectLabel>

                {MOCK_LOCATIONS.map((location) => (
                  <SelectItem key={location.id} value={location.id}>{location.name}</SelectItem>
                ))}
              </SelectGroup>
            </SelectContent>
          </Select>
        </form>
      </Form>

      <p className="text-sm text-muted-foreground">
        <Trans i18nKey={'cart:locations.description'} />
      </p>

    </div>
  )
}
