"use client";
import { useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import Swal from "sweetalert2";
import { UseMutate } from "@/hooks/UseMutate";
import { Form } from "@/shared/ui/form";
import FormStaticSelect from "@/shared/form-controls/FormStaticSelect";
import FormGenralSelect from "@/shared/form-controls/FormGenralSelect";
import FormInput from "@/shared/form-controls/FormInput";
import FormDate from "@/shared/form-controls/FormDate";
import FormPhoneNumber from "@/shared/form-controls/FormPhoneNumber";
import FormCheckbox from "@/shared/form-controls/FormCheckbox";
import { Subscription } from "@/interfaces/types";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import dayjs from "dayjs";
import AppButton from "@/shared/buttons/AppButton";
import FormTime from "@/shared/form-controls/FormTime";

export default function SubscriptionForm({
  subscription_id,
  data,
}: {
  subscription_id: string;
  data: Subscription;
}) {
  const t = useTranslations("");

  const formSchema = Yup.object({
    name: Yup.string()
      .required(t("validations.requiredField", { field: t("LABELS.name") }))
      .matches(
        /^\s*\S+(?:\s+\S+)+\s*$/,
        t("validations.The value must be two words"),
      )
      .max(
        250,
        t("validations.The full name must be less than 250 characters"),
      ),
    username: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.username") }),
    ),
    address_id: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.address") }),
    ),
    product_id: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.product") }),
    ),
    start_date: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.from_start_date") }),
    ),
    end_date: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.to_end_date") }),
    ),
    phone_limit: Yup.number(),
    phone: Yup.string()
      .required(t("validations.requiredField", { field: t("LABELS.phone") }))
      .test((value, context) => {
        let phoneLimit = context.parent.phone_limit;

        if (!phoneLimit) return true;
        if (value && value.length !== parseInt(phoneLimit)) {
          return context.createError({
            message: t("validations.phoneLimit", {
              length: `${phoneLimit}`,
            }),
            path: "phone",
          });
        }
        return true;
      }),
    phone_code: Yup.string(),
    payment_type: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.payment_type") }),
    ),
    card_info: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.card_info") }),
    ),
    shipping_time: Yup.string().required(
      t("validations.requiredField", { field: t("LABELS.shipping_time") }),
    ),
    terms: Yup.boolean()
      .required(t("validations.requiredField", { field: t("LABELS.terms") }))
      .oneOf(
        [true],
        t("validations.requiredField", { field: t("LABELS.agree") }),
      ),
  });

  const form = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      name: "",
      username: "",
      address_id: "",
      product_id: "",
      start_date: "",
      end_date: "",
      phone: "",
      phone_limit: 9,
      phone_code: "",
      payment_type: "",
      card_info: "",
      shipping_time: "",
      terms: false,
    },
  });
  const { setValue, trigger, watch } = form;
  const start_date = watch("start_date");

  const { mutate, isLoading } = UseMutate({
    endpoint: "client/user-subscriptions",
    onSuccess: (responseData: any) => {
      ShowAlertMixin({
        icon: "success",
        title: responseData?.message,
      });
    },
  });
  const handleSubmit = async (values: Yup.InferType<typeof formSchema>) => {
    await mutate({ ...values, subscription_id });
  };
  return (
    <div className="min-h-screen bg-white lg:pt-32 pt-20">
      <div className="max-w-3xl mx-auto px-4">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-semibold mb-4 text-text-primary">
            {t("subscription_form.title")}
          </h1>
          <p className="text-text-secondary">
            {t("subscription_form.description")}
          </p>
        </div>
        <div className="bg-primary/20 rounded-3xl p-8 mb-8">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
            <div className="flex-1">
              <h2 className="text-2xl mb-2 text-text-primary">{data?.name}</h2>
              <p className="text-text-secondary">{data?.description}</p>
            </div>
            <div className="text-center bg-white rounded-2xl px-8 py-6 shadow-sm">
              <div
                className="flex items-baseline gap-2 justify-center mb-1"
                dir="ltr"
              >
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 240 240"
                  fill="none"
                  className="flex-shrink-0 *:fill-text-primary"
                >
                  <path d="M79.5601 178.8C76.8801 178.8 74.6401 178.08 72.8401 176.64C71.0401 175.2 69.9201 173.28 69.4801 170.88L57.1201 107.52C56.6801 105.36 57.0401 103.52 58.2001 102C59.3601 100.48 61.0001 99.72 63.1201 99.72H75.0001L81.1201 72.96C82.2401 68.4 84.4001 64.8 87.6001 62.16C90.8001 59.52 94.8401 58.2 99.7201 58.2H136.8C141.68 58.2 145.72 59.52 148.92 62.16C152.12 64.8 154.28 68.4 155.4 72.96L161.52 99.72H173.4C175.52 99.72 177.16 100.48 178.32 102C179.48 103.52 179.84 105.36 179.4 107.52L167.04 170.88C166.6 173.28 165.48 175.2 163.68 176.64C161.88 178.08 159.64 178.8 156.96 178.8H79.5601ZM85.6801 70.68L81.6001 89.04C81.3601 90.08 81.2401 91.08 81.2401 92.04C81.2401 95.32 82.3601 98.08 84.6001 100.32C86.8401 102.56 89.6001 103.68 92.8801 103.68H143.64C146.92 103.68 149.68 102.56 151.92 100.32C154.16 98.08 155.28 95.32 155.28 92.04C155.28 91.08 155.16 90.08 154.92 89.04L150.84 70.68C150.36 68.52 149.36 66.8 147.84 65.52C146.32 64.24 144.48 63.6 142.32 63.6H94.2001C92.0401 63.6 90.2001 64.24 88.6801 65.52C87.1601 66.8 86.1601 68.52 85.6801 70.68ZM82.2001 173.4H154.32L165.36 115.2H71.1601L82.2001 173.4Z"></path>
                </svg>
                <span className="text-3xl font-normal text-primary tracking-tight">
                  {t("Text.SR")} {data?.price}
                </span>
              </div>
              <p className="text-sm text-text-secondary">
                {data?.period_formatted}
              </p>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div className="text-center">
              <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center mx-auto mb-2">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="lucide lucide-calendar text-primary"
                >
                  <path d="M8 2v4"></path>
                  <path d="M16 2v4"></path>
                  <rect width="18" height="18" x="3" y="4" rx="2"></rect>
                  <path d="M3 10h18"></path>
                </svg>
              </div>
              <p className="text-xs text-text-secondary">
                {t("subscription_form.delivery_date")}
              </p>
              <p className="text-sm text-text-primary">
                {t("subscription_form.delivery_date_value")}
              </p>
            </div>
            <div className="text-center">
              <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center mx-auto mb-2">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="lucide lucide-truck text-primary"
                >
                  <path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"></path>
                  <path d="M15 18H9"></path>
                  <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"></path>
                  <circle cx="17" cy="18" r="2"></circle>
                  <circle cx="7" cy="18" r="2"></circle>
                </svg>
              </div>
              <p className="text-xs text-text-secondary">
                {t("subscription_form.free_delivery")}
              </p>
              <p className="text-sm text-text-primary">
                {t("subscription_form.free_delivery_value")}
              </p>
            </div>
            <div className="text-center">
              <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center mx-auto mb-2">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="20"
                  height="20"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="lucide lucide-flower2 lucide-flower-2 text-primary"
                >
                  <path d="M12 5a3 3 0 1 1 3 3m-3-3a3 3 0 1 0-3 3m3-3v1M9 8a3 3 0 1 0 3 3M9 8h1m5 0a3 3 0 1 1-3 3m3-3h-1m-2 3v-1"></path>
                  <circle cx="12" cy="8" r="2"></circle>
                  <path d="M12 10v12"></path>
                  <path d="M12 22c4.2 0 7-1.667 7-5-4.2 0-7 1.667-7 5Z"></path>
                  <path d="M12 22c-4.2 0-7-1.667-7-5 4.2 0 7 1.667 7 5Z"></path>
                </svg>
              </div>
              <p className="text-xs text-text-secondary">
                {t("subscription_form.fresh_flowers")}
              </p>
              <p className="text-sm text-text-primary">
                {t("subscription_form.fresh_flowers_value")}
              </p>
            </div>
          </div>
        </div>
        <div className="bg-white border border-gray-200/30 rounded-3xl p-8">
          <h3 className="text-2xl mb-6 text-text-primary text-center">
            {t("subscription_form.form_title")}
          </h3>
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(handleSubmit)}
              className="space-y-6"
            >
              <FormInput
                name="name"
                label="name"
                placeholder="name"
                className="border-border!"
              />
              <FormInput
                name="username"
                label="username"
                placeholder="username"
                className="border-border!"
              />
              <FormGenralSelect
                name="address_id"
                label="address"
                placeholder="address"
                endpoint="client/addresses?paginate=0"
                className="border-border!"
              />
              <FormStaticSelect
                name="product_id"
                label="product"
                placeholder="product"
                options={
                  data?.products?.map((ele) => ({
                    value: String(ele.id),
                    label: ele.name,
                  })) ?? []
                }
                className="border-border!"
              />
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormDate
                  name="start_date"
                  label="from_start_date"
                  placeholder="start_date"
                  maxDate=""
                  minDate={dayjs(new Date()).format("YYYY-MM-DD")}
                  className="border-border!"
                />
                <FormDate
                  name="end_date"
                  label="to_end_date"
                  placeholder="end_date"
                  maxDate=""
                  minDate={dayjs(start_date).add(1, "day").format("YYYY-MM-DD")}
                  disabled={!start_date}
                  className="border-border!"
                />
              </div>
              <FormTime
                name="shipping_time"
                label="shipping_time"
                placeholder="shipping_time"
                className="border-border!"
              />
              <FormPhoneNumber
                name="phone"
                label="phone"
                className="border-border!"
              />
              <FormStaticSelect
                name="payment_type"
                label="payment_type"
                placeholder="payment_type"
                options={[
                  {
                    value: "credit",
                    label: t("subscription_form.payment_credit"),
                  },
                  { value: "mada", label: t("subscription_form.payment_mada") },
                  {
                    value: "apple",
                    label: t("subscription_form.payment_apple"),
                  },
                  { value: "stc", label: t("subscription_form.payment_stc") },
                ]}
                className="border-border!"
              />
              <FormInput
                name="card_info"
                label="card_info"
                placeholder="card_info"
                className="border-border!"
              />
              <FormCheckbox
                name="terms"
                onCheckedChange={(checked) => {
                  setValue("terms", checked === true);
                  trigger("terms");
                }}
                label={
                  <label
                    htmlFor="terms"
                    className="text-sm text-text-secondary cursor-pointer"
                  >
                    {t("subscription_form.terms_label")}
                  </label>
                }
                className="border-border!"
              />
              <AppButton
                title={t("subscription_form.submit")}
                buttonType="submit"
                loader={isLoading}
                disabled={isLoading}
                button
                className=" !w-full !h-[56px] !rounded-2xl  !mt-[20px]"
              />
            </form>
          </Form>
        </div>
      </div>
    </div>
  );
}
