"use client";

import { FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
import { motion } from "framer-motion";
import { Card, CardContent } from "@/components/ui/card";
import LabelAndInput from "@/components/form-components/label-and-input";
import LabelAndRadio from "@/components/form-components/label-and-radio";
import SectionTitle from "@/components/section-title";
import { useTranslations, useLocale } from "next-intl";
import { Button } from "@/components/ui/button";
import { BeatLoader } from "react-spinners";
import { Label } from "@/components/ui/label";
import { FaShippingFast, FaAmazonPay, FaCreditCard } from "react-icons/fa";
import { Check } from "lucide-react";
import Image from "next/image";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { resetStatus } from "@/store/slices/cart-slice";
import type { AppDispatch, RootState } from "@/store/store";
import {
  getCheckoutForm,
  setSelectedPaymentMethod,
  setSelectedShippingMethod,
  getAddresses,
  deleteAddress,
  resetCheckoutState
} from "@/store/slices/checkout-slice";
import AddressList from "@/components/checkout/AddressList";

interface ShippingFormProps {
  submitLabel?: string;
  isSubmitting?: boolean;
  isLoading?: boolean;
  form: any;
  status: string | null;
  data: any;
  watch: any;
  orderReviewed?: boolean;
  orderReview?: any;
  onReview?: () => void;
  onPlaceOrder?: () => void;
}

export default function ShippingForm({
  isSubmitting,
  isLoading: initialLoading,
  form,
  submitLabel,
  watch,
  orderReviewed,
  orderReview,
  onReview,
  onPlaceOrder,
}: ShippingFormProps) {
  const t = useTranslations("cart");
  const locale = useLocale();
  const isRtl = locale === "ar";
  const dispatch = useDispatch<AppDispatch>();
  const tButtons = useTranslations("buttons");
  const { shippingMethods, paymentMethods, addresses, isLoading: checkoutLoading } = useSelector(
    (state: RootState) => state.checkout
  );
  const { isAuthenticated } = useSelector((state: RootState) => state.auth);

  const selectedPaymentMethod = form.watch("payment.method");
  const isNewAddress = form.watch("is_new_address");
  const selectedAddressId = form.watch("addressId");

  useEffect(() => {
    dispatch(resetStatus());
    dispatch(getCheckoutForm() as any);
    if (isAuthenticated) {
      dispatch(getAddresses() as any);
    }
  }, [dispatch, isAuthenticated]);

  // If user has addresses and none selected yet, pick the first one and set is_new_address to false
  useEffect(() => {
    if (isAuthenticated && addresses.length > 0 && !selectedAddressId) {
      form.setValue("addressId", String(addresses[0].id));
      form.setValue("is_new_address", false);
    }
  }, [addresses, isAuthenticated, selectedAddressId, form]);

  // If backend returns methods, default-select first options (once)
  useEffect(() => {
    if (!form.getValues("shipping_method") && Array.isArray(shippingMethods) && shippingMethods.length > 0) {
      const first = shippingMethods[0];
      const code = String(first?.code || first?.methods?.code || "flatrate_flatrate");
      form.setValue("shipping_method", code, { shouldValidate: true, shouldDirty: true });
    }
  }, [shippingMethods, form]);

  useEffect(() => {
    if (!form.getValues("payment.method") && Array.isArray(paymentMethods) && paymentMethods.length > 0) {
      const first = paymentMethods[0];
      const code = String(first?.code || "cashondelivery");
      form.setValue("payment.method", code, { shouldValidate: true, shouldDirty: true });
    }
  }, [paymentMethods, form]);
  return (
    <motion.div 
      initial={{ opacity: 0, y: 8 }} 
      animate={{ opacity: 1, y: 0 }}
      dir={isRtl ? "rtl" : "ltr"}
      className={isRtl ? "text-right" : "text-left"}
    >
      <Card
        className={`w-full xl:max-w-3xl mx-auto shadow-none border-none`}
      >
        <CardContent>
          {/* Saved Addresses / New Address Toggle */}
          {isAuthenticated && addresses.length > 0 && (
            <div className="mb-4">
              <AddressList
                addresses={addresses}
                selectedAddress={selectedAddressId}
                onSelectAddress={(id) => {
                  form.setValue("addressId", String(id));
                  form.setValue("is_new_address", false);
                }}
                onDeleteAddress={(id) => dispatch(deleteAddress(String(id)) as any)}
                onAddNewAddress={() => form.setValue("is_new_address", true)}
              />

              {!isNewAddress && (
                <Button
                  type="button"
                  variant="link"
                  onClick={() => form.setValue("is_new_address", true)}
                  className="p-0 h-auto font-bold text-primary"
                >
                  {t("or-add-new-address")}
                </Button>
              )}
            </div>
          )}

          {/* Billing Information Form - Only show if new address or no addresses */}
          {(isNewAddress || addresses?.length === 0) && (
            <div className="space-y-4 my-6">
              <SectionTitle title={t("billing-information")} />

              {isAuthenticated && addresses.length > 0 && (
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => form.setValue("is_new_address", false)}
                  className="mb-4 rounded-xl"
                >
                  {t("back-to-saved-addresses")}
                </Button>
              )}

              <div className="gap-4 grid grid-cols-1 md:grid-cols-2 mt-4">
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.first_name"
                  labelText={t("first-name")}
                  inputPlaceholder={t("placeholder-first-name")}
                  inputType="text"
                  inputId="billing-first-name"
                />
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.last_name"
                  labelText={t("last-name")}
                  inputPlaceholder={t("placeholder-last-name")}
                  inputType="text"
                  inputId="billing-last-name"
                />
              </div>

              <div className="gap-4 grid grid-cols-1 md:grid-cols-2">
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.email"
                  labelText={t("email")}
                  inputPlaceholder={t("placeholder-email")}
                  inputType="email"
                  inputId="billing-email"
                />
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.address1"
                  labelText={t("address")}
                  inputPlaceholder={t("placeholder-address")}
                  inputType="text"
                  inputId="billing-address"
                />
              </div>

              <div className="gap-4 grid grid-cols-1 md:grid-cols-2">
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.city"
                  labelText={t("city")}
                  inputPlaceholder={t("placeholder-city")}
                  inputType="text"
                  inputId="billing-city"
                />
                <LabelAndInput
                  control={form.control}
                  fieldName="billing.phone"
                  labelText={t("phone")}
                  inputPlaceholder={t("placeholder-phone")}
                  inputType="tel"
                  inputId="billing-phone"
                />
              </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
              <FormField
                control={form.control}
                name="billing.country"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("country")}</FormLabel>
                    <FormControl>
                      <select
                        {...field}
                        id="billing-country"
                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      >
                        <option value="EG">{t("country-eg")}</option>
                        <option value="SA">{t("country-sa")}</option>
                        <option value="AE">{t("country-ae")}</option>
                        <option value="KW">{t("country-kw")}</option>
                        <option value="BH">{t("country-bh")}</option>
                        <option value="QA">{t("country-qa")}</option>
                        <option value="OM">{t("country-om")}</option>
                        <option value="JO">{t("country-jo")}</option>
                      </select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          {/* Same as Billing Checkbox */}
          <div className="flex items-center gap-2 my-6">
            <input
              type="checkbox"
              name="billing.use_for_shipping"
              checked={form.watch("billing.use_for_shipping")}
              onChange={(e) =>
                form.setValue("billing.use_for_shipping", e.target.checked)
              }
              id="same-as-billing"
              className="mr-2 accent-primary"
            />
            <Label htmlFor="same-as-billing" className="font-medium text-sm">
              {t("same-as-billing")}
            </Label>
          </div>

          {/* Shipping Information */}
          {!form.watch("billing.use_for_shipping") && (
            <div className="my-6">
              <SectionTitle title={t("shipping-information")} />

              <div className="gap-4 grid grid-cols-1 md:grid-cols-2 mt-4">
                <LabelAndInput
                  control={form.control}
                  fieldName="shipping.address1"
                  labelText={t("address")}
                  inputPlaceholder={t("placeholder-address")}
                  inputType="text"
                  inputId="shipping-address"
                />
                <LabelAndInput
                  control={form.control}
                  fieldName="shipping.city"
                  labelText={t("city")}
                  inputPlaceholder={t("placeholder-city")}
                  inputType="text"
                  inputId="shipping-city"
                />
              </div>

              <div className="mt-4">
                <LabelAndInput
                  control={form.control}
                  fieldName="shipping.phone"
                  labelText={t("phone")}
                  inputPlaceholder={t("placeholder-phone")}
                  inputType="tel"
                  inputId="shipping-phone"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                <FormField
                  control={form.control}
                  name="shipping.country"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("country")}</FormLabel>
                      <FormControl>
                        <select
                          {...field}
                          id="shipping-country"
                          className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                        >
                          <option value="EG">{t("country-eg")}</option>
                          <option value="SA">{t("country-sa")}</option>
                          <option value="AE">{t("country-ae")}</option>
                          <option value="KW">{t("country-kw")}</option>
                          <option value="BH">{t("country-bh")}</option>
                          <option value="QA">{t("country-qa")}</option>
                          <option value="OM">{t("country-om")}</option>
                          <option value="JO">{t("country-jo")}</option>
                        </select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>
          )}

          {/* Shipping & Payment Methods */}
          <div className="flex flex-col space-y-6">
            {/* Shipping Method */}
            <Accordion type="single" collapsible>
              <AccordionItem value="shipping-method">
                <AccordionTrigger className="px-3 border border-gray-200">
                  <div className="flex items-center gap-2">
                    <FaShippingFast size={22} className="text-primary" />
                    <SectionTitle
                      title={t("shipping-method")}
                      titleStyle="font-semibold lg:text-lg"
                    />
                  </div>
                </AccordionTrigger>
                <AccordionContent className="mt-3 p-3 border border-gray-200 rounded-md">
                  <LabelAndRadio
                    control={form.control}
                    inputName="shipping_method"
                    labelText={t("choose-shipping-method")}
                    options={
                      Array.isArray(shippingMethods) && shippingMethods.length > 0
                        ? shippingMethods.map((m: any) => ({
                          value: String(m?.code || m?.methods?.code || ""),
                          label: String(m?.title || m?.methods?.title || m?.label || t("normal-shipping")),
                          disable: Boolean(m?.disable),
                        })).filter((o: any) => o.value)
                        : [
                          {
                            value: "flatrate_flatrate",
                            label: t("normal-shipping"),
                          },
                        ]
                    }
                    onChange={(val) => {
                      const method = shippingMethods.find((m: any) => (m?.code || m?.methods?.code) === val);
                      if (method) dispatch(setSelectedShippingMethod(method));
                    }}
                    itemClassName="justify-end"
                  />
                </AccordionContent>
              </AccordionItem>
            </Accordion>

            {/* Payment Method */}
            <Accordion type="single" collapsible>
              <AccordionItem value="payment-way">
                <AccordionTrigger className="px-3 border border-gray-200">
                  <div className="flex items-center gap-2">
                    <FaAmazonPay size={24} className="text-primary" />
                    <SectionTitle
                      title={t("payment-method")}
                      titleStyle="font-semibold lg:text-lg"
                    />
                  </div>
                </AccordionTrigger>
                <AccordionContent className="mt-3 p-3 border border-gray-200 rounded-md">
                  <LabelAndRadio
                    control={form.control}
                    inputName="payment.method"
                    labelText={t("payment-method")}
                    options={
                      Array.isArray(paymentMethods) && paymentMethods.length > 0
                        ? paymentMethods.map((m: any) => ({
                          value: String(m?.code || ""),
                          label: String(m?.title || m?.name || m?.label || m?.code || ""),
                          disable: Boolean(m?.disable),
                        })).filter((o: any) => o.value)
                        : [
                          { value: "cashondelivery", label: t("cash-on-delivery") },
                          { value: "moyasar", label: t("credit-card") },
                        ]
                    }
                    onChange={(val) => {
                      const method = paymentMethods.find((m: any) => m?.code === val);
                      if (method) dispatch(setSelectedPaymentMethod(method));
                    }}
                    itemClassName="justify-end"
                  />

                </AccordionContent>

              </AccordionItem>
            </Accordion>

            {/* Online Payment Methods (if credit card selected) */}
            {selectedPaymentMethod === "moyasar" || selectedPaymentMethod === "tabby" ? (
              <Accordion type="single" collapsible>
                <AccordionItem value="online-payment-methods">
                  <AccordionTrigger className="px-3 border border-gray-200">
                    <div className="flex items-center gap-2">
                      <FaCreditCard size={24} className="text-primary" />
                      <SectionTitle
                        title={t("online-payment-methods")}
                        titleStyle="font-semibold lg:text-lg"
                      />
                    </div>
                  </AccordionTrigger>
                  <AccordionContent className="mt-3 p-3 border border-gray-200 rounded-md">
                    <div className="text-gray-600 text-sm">
                      {initialLoading ? tButtons("loading") : t("payment-method")}
                    </div>
                  </AccordionContent>
                </AccordionItem>
              </Accordion>
            ) : null}
          </div>

          {orderReviewed && orderReview?.totalsData && (
            <div className="bg-gray-50 mt-6 p-4 border border-gray-100 rounded-lg">
              <h4 className="mb-3 font-bold text-gray-900">{t("order-summary")}</h4>
              <div className="space-y-2">
                {orderReview.totalsData.map((row: any, idx: number) => (
                  <div key={idx} className="flex justify-between items-center text-sm">
                    <span className="text-gray-600">{row.title}</span>
                    <span className="font-bold text-gray-900">{row.formattedValue}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {initialLoading ? (
            <div className="flex justify-center py-8">
              <BeatLoader color="#F97316" size={8} />
            </div>
          ) : (
            <div className="flex sm:flex-row flex-col gap-3 mt-8">
              {!orderReviewed ? (
                <Button
                  type="button"
                  onClick={onReview}
                  disabled={isSubmitting || checkoutLoading}
                  className="group bg-black hover:bg-black/90 shadow-md rounded-xl w-full h-12 font-bold text-white transition-all"
                >
                  {isSubmitting || checkoutLoading ? <BeatLoader color="#fff" size={8} /> : (
                    <span className="flex items-center gap-2">
                      {t("review_order")}
                    </span>
                  )}
                </Button>
              ) : (
                <div className="flex gap-3 w-full">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => dispatch(resetCheckoutState())}
                    disabled={isSubmitting || checkoutLoading}
                    className="flex-1 hover:bg-gray-50 border-gray-200 rounded-xl h-12 font-semibold transition-colors"
                  >
                    {tButtons("edit")}
                  </Button>
                  <Button
                    type="button"
                    onClick={onPlaceOrder}
                    disabled={isSubmitting || checkoutLoading}
                    className="flex-[2] bg-primary hover:bg-primary/90 shadow-lg rounded-xl h-12 font-bold text-white transition-all"
                  >
                    {isSubmitting || checkoutLoading ? <BeatLoader color="#fff" size={8} /> : (
                      <span className="flex items-center gap-2">
                        <Check className="w-5 h-5" />
                        {t("complete-purchase")}
                      </span>
                    )}
                  </Button>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </motion.div>
  );
}
