import { ErrorOverlay, FormPercentageField, FormTextAreaField, LoadingOverlay } from "@/components";
import {
  Alert,
  AlertDescription,
  AlertTitle,
  Button,
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
  Form,
  Input,
  Label,
} from "@/ui";

import { t } from "i18next";
import { AlertCircleIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { Trans } from "react-i18next";

import { useUnsavedChangesNotifier } from "@/lib/hooks";
import { cn } from "@/lib/utils";
import { useToast } from "@/ui/use-toast";
import { IUpdateProfile_Request_DTO } from "@shared/contexts";
import { useSettings } from "./hooks";

type SettingsDataForm = IUpdateProfile_Request_DTO;

export const SettingsEditor = () => {
  const [activeSection, setActiveSection] = useState("profile");
  const { useOne, useUpdate, useUploadLogo } = useSettings();
  const { toast } = useToast();

  const { data, status, error: queryError } = useOne();

  const defaultValues = useMemo(
    () => ({
      contact_information: "",
      default_payment_method: "",
      default_notes: "",
      default_legal_terms: "",
      default_quote_validity: "",
      default_tax: {
        amount: undefined,
        scale: 2,
      },
    }),
    []
  );

  const { mutate } = useUpdate();
  const { upload } = useUploadLogo();

  const form = useForm<SettingsDataForm>({
    mode: "onBlur",
    values: data?.dealer,
    defaultValues,
    /*resolver: joiResolver(
      Joi.object({
        contact_information: Joi.string().optional().allow(null).allow("").default(""),
        default_payment_method: Joi.string().optional().allow(null).allow("").default(""),
        default_notes: Joi.string().optional().allow(null).allow("").default(""),
        default_legal_terms: Joi.string().optional().allow(null).allow("").default(""),
        default_quote_validity: Joi.string().optional().allow(null).allow("").default(""),
        default_tax: Joi.object({
          amount: Joi.number().allow(null),
          scale: Joi.number(),
        }).required(),
      })
    ),*/
  });

  const { formState, reset, getValues, handleSubmit } = form;
  const { isSubmitting, isDirty } = formState;

  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    if (file) {
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        alert(t("settings.form_fields.logo.invalid_format"));
        return;
      }

      const reader = new FileReader();
      reader.onloadend = () => {
        const img = new Image();
        img.onload = () => {
          const width = img.width;
          const height = img.height;

          // Comprobar que la imagen tiene una proporción de 2:1 (ancho:alto)
          const isProportional = width / height === 2;

          // Comprobar que las dimensiones son iguales o mayores a 200x100 y proporcionales
          if (width < 200 || height < 100 || !isProportional) {
            alert(t("settings.form_fields.logo.invalid_dimensions"));
          } else {
            upload(file);
          }
        };
        img.src = reader.result as string;
      };
      reader.readAsDataURL(file);
    }
  };

  useUnsavedChangesNotifier({
    isDirty,
  });

  const onSubmit: SubmitHandler<SettingsDataForm> = async (data) => {
    mutate(data, {
      onError: (error) => {
        console.debug(error);
        toast({ title: "Error", description: error.message, variant: "destructive" });
        //alert(error.message);
      },
      //onSettled: () => {},
      onSuccess: () => {
        reset(getValues());
        toast({ description: "Ajustes guardados", variant: "success" });
      },
    });
  };

  if (isSubmitting) {
    return <LoadingOverlay title='Guardando ajustes' />;
  }

  if (status === "error") {
    return <ErrorOverlay errorMessage={queryError.message} />;
  }

  if (status !== "success") {
    return <LoadingOverlay />;
  }

  return (
    <Form {...form}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className='mx-auto grid w-full max-w-6xl items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]'>
          {form.formState.errors.root?.message && (
            <Alert variant='destructive'>
              <AlertCircleIcon className='w-4 h-4' />
              <AlertTitle>
                <Trans i18nKey='common.error' />
              </AlertTitle>
              <AlertDescription>{form.formState.errors.root?.message}</AlertDescription>
            </Alert>
          )}

          <nav className='grid gap-4 text-sm text-muted-foreground'>
            <a
              onClick={() => setActiveSection("profile")}
              className={
                activeSection === "profile" ? "font-semibold text-primary" : "cursor-pointer"
              }
            >
              <Trans i18nKey='settings.edit.tabs.profile' />
            </a>
            <a
              onClick={() => setActiveSection("quotes")}
              className={
                activeSection === "quotes" ? "font-semibold text-primary" : "cursor-pointer "
              }
            >
              <Trans i18nKey='settings.edit.tabs.quotes' />
            </a>
            <a
              onClick={() => setActiveSection("legal")}
              className={
                activeSection === "legal" ? "font-semibold text-primary" : "cursor-pointer "
              }
            >
              <Trans i18nKey='settings.edit.tabs.legal' />
            </a>
          </nav>
          <div className={cn("grid gap-6", activeSection === "profile" ? "visible" : "hidden")}>
            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.contact_information.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.contact_information.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextAreaField
                  //autoSize
                  rows={8}
                  placeholder={t("settings.form_fields.contact_information.placeholder")}
                  name='contact_information'
                  required
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.logo.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.logo.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className='flex items-center space-x-4'>
                  <div className='w-[400px] h-[200px] border border-gray-300 flex items-center justify-center overflow-hidden'>
                    <img
                      src={
                        data.dealer.logo ? data.dealer.logo : "https://via.placeholder.com/200x100"
                      }
                      width={400}
                      height={200}
                      style={{ objectFit: "contain" }}
                    />
                  </div>
                  <div>
                    <p className='mt-2 text-sm text-gray-500'>
                      <Trans i18nKey='settings.form_fields.logo.requirements' />
                    </p>
                  </div>
                </div>
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Label
                  htmlFor='logo-upload'
                  className='inline-flex items-center justify-center h-10 px-4 py-2 text-sm font-medium transition-colors rounded-md cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90 whitespace-nowrap ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50'
                >
                  <Trans i18nKey='settings.form_fields.logo.upload' />
                </Label>

                <Input
                  id='logo-upload'
                  type='file'
                  accept='.png,.jpg,.jpeg'
                  onChange={handleLogoChange}
                  className='hidden'
                />
              </CardFooter>
            </Card>
          </div>
          <div className={cn("grid gap-6", activeSection === "quotes" ? "visible" : "hidden")}>
            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.default_tax.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.default_tax.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormPercentageField
                  scale={2}
                  disabled={formState.disabled}
                  placeholder={t("settings.form_fields.default_tax.desc")}
                  name='default_tax'
                  required
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.default_payment_method.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.default_payment_method.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextAreaField
                  autoSize
                  placeholder={t("settings.form_fields.default_payment_method.placeholder")}
                  name='default_payment_method'
                  required
                  errors={form.formState.errors}
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.default_quote_validity.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.default_quote_validity.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextAreaField
                  autoSize
                  placeholder={t("settings.form_fields.default_quote_validity.placeholder")}
                  name='default_quote_validity'
                  required
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.default_notes.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.default_notes.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextAreaField
                  autoSize
                  placeholder={t("settings.form_fields.default_notes.placeholder")}
                  name='default_notes'
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>
          </div>
          <div className={cn("grid gap-6", activeSection === "legal" ? "visible" : "hidden")}>
            <Card className='h-'>
              <CardHeader>
                <CardTitle>
                  <Trans i18nKey='settings.form_fields.default_legal_terms.label' />
                </CardTitle>
                <CardDescription>
                  <Trans i18nKey='settings.form_fields.default_legal_terms.desc' />
                </CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextAreaField
                  //autoSize
                  rows={25}
                  placeholder={t("settings.form_fields.default_legal_terms.placeholder")}
                  name='default_legal_terms'
                />
              </CardContent>
              <CardFooter className='px-6 py-4 border-t'>
                <Button>
                  <Trans i18nKey='common.save' />
                </Button>
              </CardFooter>
            </Card>
          </div>
        </div>
      </form>
    </Form>
  );
};
