import { ArchiveIcon, CopyIcon, DownloadIcon, EditIcon } from "lucide-react";

import { ButtonGroup } from "@/components";
import { useCustomLocalization } from "@/lib/hooks";
import { cn } from "@/lib/utils";
import {
  Button,
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
  Separator,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/ui";
import { useToast } from "@/ui/use-toast";
import { formatDateToYYYYMMDD } from "@shared/utilities/helpers";
import { t } from "i18next";
import { useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useQuotes } from "../hooks";
import { DownloadQuoteDialog } from "./DownloadQuoteDialog";
import { QuotePDFPreview } from "./QuotePDFPreview";
import { QuoteSentToEditor, QuoteStatusEditor } from "./editors";

type QuoteResumeProps = {
  quoteId?: string;
  className?: string;
};

export const QuoteResume = ({ quoteId, className }: QuoteResumeProps) => {
  const navigate = useNavigate();
  const { toast } = useToast();

  const { useOne, useSetStatus, useSentTo, useDownloader, useDuplicate, getQuotePDFFilename } =
    useQuotes();
  const { data, status } = useOne(quoteId);
  const { mutate: setStatusMutation } = useSetStatus();
  const { mutate: sentToMutation } = useSentTo(quoteId);
  const { mutate: duplicate } = useDuplicate();
  const { download, ...downloadProps } = useDownloader();

  const { formatCurrency, formatNumber } = useCustomLocalization({
    locale: data?.lang_code || "ES",
  });

  /*const currency_symbol = useMemo(() => {
    const currencyOrError = data
      ? CurrencyData.createFromCode(data?.currency_code)
      : CurrencyData.createDefaultCode();
    return currencyOrError.isSuccess ? currencyOrError.object.symbol : "";
  }, [data]);*/

  const totals = useMemo(() => {
    return data
      ? {
          subtotal_price: formatCurrency(data.subtotal_price),

          discount: formatNumber(data.discount),
          discount_price: formatCurrency(data.discount_price),

          tax: formatNumber(data.tax),
          tax_price: formatCurrency(data.tax_price),
          total_price: formatCurrency(data.total_price),
        }
      : {
          subtotal_price: "0,00 €",
          discount: "0",
          discount_price: "0,00 €",
          tax: "0",
          tax_price: "0,00 €",
          total_price: "0,00 €",
        };
  }, [data]);

  const allowToSent = useMemo(() => data?.status === "accepted" && !data?.date_sent, [data]);
  const isSent = useMemo(() => data?.status === "accepted" && !!data?.date_sent, [data]);

  const handleOnChangeStatus = (newStatus: string) => {
    setStatusMutation(
      { id: data!!.id, newStatus },

      {
        onSuccess: () => {
          toast({
            description: t("quotes.quote_status_editor.toast_status_changed"),
            variant: "success",
          });
        },
      }
    );
  };

  const handleOnSentTo = (_: string) => {
    sentToMutation(
      { sent_date: formatDateToYYYYMMDD(new Date()) },
      {
        onSuccess: () => {
          toast({
            description: t("quotes.quote_sent_to_editor.toast_status_changed"),
            variant: "success",
          });
        },
      }
    );
  };

  const handleFinishDownload = useCallback(() => {
    toast({
      description: t("quotes.downloading_dialog.toast_success"),
      variant: "success",
    });
  }, [toast]);

  const handleDownload = useCallback(() => {
    if (data) download(data.id, getQuotePDFFilename(data));
  }, [data]);

  if (status === "error") {
    return null;
  }

  if (status !== "success") {
    return null;
  }

  if (!data) {
    return (
      <Card className={cn("overflow-hidden", className)}>
        <CardContent className='px-4 py-6 text-center'>
          <p className='mx-auto'>Select a quote</p>
        </CardContent>
      </Card>
    );
  }

  const handleDuplicateQuote = (id: string) => {
    duplicate(
      {
        id,
      },
      {
        onSuccess(data) {
          toast({
            description: t("quotes.duplicate_action.toast_success"),
            variant: "success",
          });

          navigate(`/quotes/edit/${data.id}`, { relative: "path" });
        },
      }
    );
  };

  const handleArchiveQuote = (id: string) => {
    setStatusMutation(
      { id, newStatus: "archived" },

      {
        onSuccess: () => {
          toast({
            description: t("quotes.quote_status_editor.toast_status_changed", {
              newStatus: t("quotes.status.archived"),
            }),
            variant: "success",
          });
        },
      }
    );
  };

  return (
    <>
      <DownloadQuoteDialog {...downloadProps} onFinishDownload={handleFinishDownload} />
      <Tabs defaultValue='resume'>
        <Card className='w-[390px] overflow-hidden'>
          <CardHeader className='gap-3 border-b bg-accent'>
            <CardTitle className='flex items-center justify-between text-lg'>
              <span>{t("quotes.list.resume.title")}</span>
              <QuoteStatusEditor
                status={data.status}
                onChangeStatus={handleOnChangeStatus}
                type='badge'
              />
            </CardTitle>
            <div className='flex w-full mr-auto text-foreground'>
              <div className='flex justify-between w-full'>
                <ButtonGroup className='gap-0'>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant='outline'
                        size='icon'
                        disabled={isSent}
                        onClick={(e) => {
                          e.preventDefault();
                          navigate(`/quotes/edit/${data.id}`, { relative: "path" });
                        }}
                      >
                        <EditIcon className='w-4 h-4' />
                        <span className='sr-only'>Editar</span>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Editar</p>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant='outline'
                        size='icon'
                        onClick={(e) => {
                          e.preventDefault();
                          handleDuplicateQuote(data.id);
                        }}
                      >
                        <CopyIcon className='w-4 h-4' />
                        <span className='sr-only'>Duplicar</span>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Duplicar</p>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button variant='outline' size='icon' onClick={handleDownload}>
                        <DownloadIcon className='w-4 h-4' />
                        <span className='sr-only'>Descargar</span>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Descargar</p>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant='outline'
                        size='icon'
                        disabled={isSent}
                        onClick={(e) => {
                          e.preventDefault();
                          handleArchiveQuote(data.id);
                        }}
                      >
                        <ArchiveIcon className='w-4 h-4' />
                        <span className='sr-only'>Archivar</span>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Archivar</p>
                    </TooltipContent>
                  </Tooltip>
                </ButtonGroup>

                <ButtonGroup>
                  <QuoteSentToEditor
                    disabled={isSent || !allowToSent}
                    id={data.id}
                    onSentTo={handleOnSentTo}
                  />
                </ButtonGroup>
              </div>
            </div>
          </CardHeader>
          <CardContent className='p-6 text-sm'>
            <TabsList className='grid w-full grid-cols-2'>
              <TabsTrigger value='resume'>{t("quotes.list.resume.tabs.resume")}</TabsTrigger>
              <TabsTrigger value='preview'>{t("quotes.list.resume.tabs.preview")}</TabsTrigger>
            </TabsList>
            <TabsContent value='resume' className='pt-4'>
              <div className='grid gap-3'>
                <div className='grid gap-3'>
                  <div className='font-semibold'>{t("quotes.list.resume.quote_information")}</div>

                  <dl className='grid gap-3'>
                    <div className='flex items-center justify-between'>
                      <dt className='text-muted-foreground'>
                        {t("quotes.form_fields.reference.label")}
                      </dt>
                      <dd className='font-medium'>{data.reference}</dd>
                    </div>
                    <div className='flex items-center justify-between'>
                      <dt className='text-muted-foreground'>
                        {t("quotes.form_fields.date.label")}
                      </dt>
                      <dd className='font-medium'>{new Date(data.date).toLocaleDateString()}</dd>
                    </div>
                    <div className='flex items-start justify-between'>
                      <dt className='text-muted-foreground whitespace-nowrap'>
                        {t("quotes.form_fields.customer_reference.label")}
                      </dt>
                      <dd className='font-medium text-right whitespace-break-spaces'>
                        {data.customer_reference}
                      </dd>
                    </div>
                  </dl>
                </div>
                <Separator className='my-4' />
                <div className='grid gap-3'>
                  <div className='font-semibold'>
                    {t("quotes.list.resume.customer_information")}
                  </div>
                  <div>{data.customer_information}</div>
                </div>
                <Separator className='my-4' />
                <div className='font-semibold'>{t("quotes.list.resume.price_information")}</div>
                <ul className='grid gap-3'>
                  <li className='flex items-center justify-between'>
                    <span className='text-muted-foreground'>
                      {t("quotes.form_fields.subtotal_price.label")}
                    </span>
                    <span>{totals.subtotal_price}</span>
                  </li>
                  <li className='flex items-center justify-between'>
                    <span className='text-muted-foreground'>
                      {t("quotes.form_fields.discount_value.label", { value: totals.discount })}
                    </span>
                    <span>{totals.discount_price}</span>
                  </li>

                  <li className='flex items-center justify-between'>
                    <span className='text-muted-foreground'>
                      {t("quotes.form_fields.tax_value.label", { value: totals.tax })}
                    </span>
                    <span>{totals.tax_price}</span>
                  </li>
                  <li className='flex items-center justify-between font-semibold'>
                    <span className='text-muted-foreground'>
                      {t("quotes.form_fields.total_price.label")}
                    </span>
                    <span>{totals.total_price}</span>
                  </li>
                </ul>
              </div>
            </TabsContent>
            <TabsContent value='preview'>
              <QuotePDFPreview quote={data} />
            </TabsContent>
          </CardContent>
          <CardFooter className='flex flex-row items-center px-6 py-3 border-t bg-accent'>
            <div className='text-xs text-muted-foreground'></div>
          </CardFooter>
        </Card>
      </Tabs>
    </>
  );
};
