"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { useTranslations, useLocale } from "next-intl";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { useSaleorCheckoutStore } from "@/stores/saleorCheckoutStore";
import { formatPrice } from "@/lib/saleor";
import { saleorClient } from "@/lib/saleor/client";
import {
  CHECKOUT_SHIPPING_ADDRESS_UPDATE,
  CHECKOUT_BILLING_ADDRESS_UPDATE,
  CHECKOUT_COMPLETE,
} from "@/lib/saleor/mutations/Checkout";
import type { Checkout } from "@/types/saleor";

interface ShippingAddressUpdateResponse {
  checkoutShippingAddressUpdate?: {
    checkout?: Checkout;
    errors?: Array<{ message: string }>;
  };
}

interface BillingAddressUpdateResponse {
  checkoutBillingAddressUpdate?: {
    checkout?: Checkout;
    errors?: Array<{ message: string }>;
  };
}

interface CheckoutCompleteResponse {
  checkoutComplete?: {
    order?: { number: string };
    errors?: Array<{ message: string }>;
  };
}

interface AddressForm {
  firstName: string;
  lastName: string;
  streetAddress1: string;
  streetAddress2: string;
  city: string;
  postalCode: string;
  phone: string;
}

export default function CheckoutPage() {
  const t = useTranslations("Checkout");
  const locale = useLocale();
  const router = useRouter();
  const { checkout, refreshCheckout, getLines, getTotal } = useSaleorCheckoutStore();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [orderComplete, setOrderComplete] = useState(false);
  const [orderNumber, setOrderNumber] = useState<string | null>(null);

  const [sameAsShipping, setSameAsShipping] = useState(true);
  const [shippingAddress, setShippingAddress] = useState<AddressForm>({
    firstName: "",
    lastName: "",
    streetAddress1: "",
    streetAddress2: "",
    city: "",
    postalCode: "",
    phone: "",
  });
  const [billingAddress, setBillingAddress] = useState<AddressForm>({
    firstName: "",
    lastName: "",
    streetAddress1: "",
    streetAddress2: "",
    city: "",
    postalCode: "",
    phone: "",
  });

  const lines = getLines();
  const total = getTotal();

  useEffect(() => {
    if (!checkout) {
      refreshCheckout();
    }
  }, [checkout, refreshCheckout]);

  const handleShippingChange = (field: keyof AddressForm, value: string) => {
    setShippingAddress((prev) => ({ ...prev, [field]: value }));
    if (sameAsShipping) {
      setBillingAddress((prev) => ({ ...prev, [field]: value }));
    }
  };

  const handleBillingChange = (field: keyof AddressForm, value: string) => {
    setBillingAddress((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!checkout) {
      setError(t("errorNoCheckout"));
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const shippingResult = await saleorClient.mutate<ShippingAddressUpdateResponse>({
        mutation: CHECKOUT_SHIPPING_ADDRESS_UPDATE,
        variables: {
          checkoutId: checkout.id,
          shippingAddress: {
            ...shippingAddress,
            country: "RS",
          },
        },
      });

      if (shippingResult.data?.checkoutShippingAddressUpdate?.errors && shippingResult.data.checkoutShippingAddressUpdate.errors.length > 0) {
        throw new Error(shippingResult.data.checkoutShippingAddressUpdate.errors[0].message);
      }

      const billingResult = await saleorClient.mutate<BillingAddressUpdateResponse>({
        mutation: CHECKOUT_BILLING_ADDRESS_UPDATE,
        variables: {
          checkoutId: checkout.id,
          billingAddress: {
            ...billingAddress,
            country: "RS",
          },
        },
      });

      if (billingResult.data?.checkoutBillingAddressUpdate?.errors && billingResult.data.checkoutBillingAddressUpdate.errors.length > 0) {
        throw new Error(billingResult.data.checkoutBillingAddressUpdate.errors[0].message);
      }

      const completeResult = await saleorClient.mutate<CheckoutCompleteResponse>({
        mutation: CHECKOUT_COMPLETE,
        variables: {
          checkoutId: checkout.id,
        },
      });

      if (completeResult.data?.checkoutComplete?.errors && completeResult.data.checkoutComplete.errors.length > 0) {
        throw new Error(completeResult.data.checkoutComplete.errors[0].message);
      }

      const order = completeResult.data?.checkoutComplete?.order;
      if (order) {
        setOrderNumber(order.number);
        setOrderComplete(true);
      } else {
        throw new Error(t("errorCreatingOrder"));
      }
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : null;
      setError(errorMessage || t("errorOccurred"));
    } finally {
      setIsLoading(false);
    }
  };

  if (orderComplete) {
    return (
      <>
        <Header locale={locale} />
        <main className="min-h-screen">
          <section className="pt-[120px] pb-20 px-4">
            <div className="max-w-2xl mx-auto text-center">
              <div className="mb-6">
                <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
                </div>
                <h1 className="text-3xl font-serif mb-2">{t("orderConfirmed")}</h1>
                <p className="text-foreground-muted">{t("thankYou")}</p>
              </div>

              {orderNumber && (
                <div className="bg-background-ice p-6 rounded-lg mb-6">
                  <p className="text-sm text-foreground-muted mb-1">{t("orderNumber")}</p>
                  <p className="text-2xl font-serif">#{orderNumber}</p>
                </div>
              )}

              <p className="text-foreground-muted mb-8">
                {t("confirmationEmail")}
              </p>

              <Link
                href={`/${locale}/products`}
                className="inline-block px-8 py-3 bg-foreground text-white hover:bg-accent-dark transition-colors"
              >
                {t("continueShoppingBtn")}
              </Link>
            </div>
          </section>
        </main>
        <div className="pt-16">
          <Footer locale={locale} />
        </div>
      </>
    );
  }

  return (
    <>
      <Header locale={locale} />
      <main className="min-h-screen">
        <section className="pt-[120px] pb-20 px-4">
          <div className="max-w-7xl mx-auto">
            <h1 className="text-3xl font-serif mb-8">{t("checkout")}</h1>

            {error && (
              <div className="bg-red-50 border border-red-200 text-red-600 p-4 mb-6 rounded">
                {error}
              </div>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
              <div>
                <form onSubmit={handleSubmit} className="space-y-6">
                  <div className="border-b border-border pb-6">
                    <h2 className="text-xl font-serif mb-4">{t("shippingAddress")}</h2>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium mb-1">{t("firstName")}</label>
                        <input
                          type="text"
                          required
                          value={shippingAddress.firstName}
                          onChange={(e) => handleShippingChange("firstName", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium mb-1">{t("lastName")}</label>
                        <input
                          type="text"
                          required
                          value={shippingAddress.lastName}
                          onChange={(e) => handleShippingChange("lastName", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div className="col-span-2">
                        <label className="block text-sm font-medium mb-1">{t("streetAddress")}</label>
                        <input
                          type="text"
                          required
                          value={shippingAddress.streetAddress1}
                          onChange={(e) => handleShippingChange("streetAddress1", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div className="col-span-2">
                        <input
                          type="text"
                          value={shippingAddress.streetAddress2}
                          onChange={(e) => handleShippingChange("streetAddress2", e.target.value)}
                          placeholder={t("streetAddressOptional")}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium mb-1">{t("city")}</label>
                        <input
                          type="text"
                          required
                          value={shippingAddress.city}
                          onChange={(e) => handleShippingChange("city", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium mb-1">{t("postalCode")}</label>
                        <input
                          type="text"
                          required
                          value={shippingAddress.postalCode}
                          onChange={(e) => handleShippingChange("postalCode", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                      <div className="col-span-2">
                        <label className="block text-sm font-medium mb-1">{t("phone")}</label>
                        <input
                          type="tel"
                          required
                          value={shippingAddress.phone}
                          onChange={(e) => handleShippingChange("phone", e.target.value)}
                          className="w-full border border-border px-4 py-2 rounded"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="border-b border-border pb-6">
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={sameAsShipping}
                        onChange={(e) => setSameAsShipping(e.target.checked)}
                        className="w-4 h-4"
                      />
                      <span>{t("billingAddressSame")}</span>
                    </label>
                  </div>

                  <button
                    type="submit"
                    disabled={isLoading || lines.length === 0}
                    className="w-full py-4 bg-foreground text-white font-medium hover:bg-accent-dark transition-colors disabled:opacity-50"
                  >
                    {isLoading ? t("processing") : t("completeOrder", { total: formatPrice(total) })}
                  </button>
                </form>
              </div>

              <div className="bg-background-ice p-6 rounded-lg h-fit">
                <h2 className="text-xl font-serif mb-6">{t("orderSummary")}</h2>

                {lines.length === 0 ? (
                  <p className="text-foreground-muted">{t("yourCartEmpty")}</p>
                ) : (
                  <>
                    <div className="space-y-4 mb-6">
                      {lines.map((line) => (
                        <div key={line.id} className="flex gap-4">
                          <div className="w-16 h-16 bg-white relative flex-shrink-0">
                            {line.variant.product.media[0]?.url && (
                              <Image
                                src={line.variant.product.media[0].url}
                                alt={line.variant.product.name}
                                fill
                                sizes="64px"
                                className="object-cover"
                              />
                            )}
                          </div>
                          <div className="flex-1">
                            <h3 className="font-medium text-sm">{line.variant.product.name}</h3>
                            <p className="text-foreground-muted text-sm">
                              {t("qty")}: {line.quantity}
                            </p>
                            <p className="text-sm">
                              {formatPrice(line.totalPrice.gross.amount)}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="border-t border-border pt-4 space-y-2">
                      <div className="flex justify-between">
                        <span className="text-foreground-muted">{t("subtotal")}</span>
                        <span>{formatPrice(checkout?.subtotalPrice?.gross?.amount || 0)}</span>
                      </div>
                      <div className="flex justify-between font-medium text-lg pt-2 border-t border-border">
                        <span>{t("total")}</span>
                        <span>{formatPrice(total)}</span>
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </section>
      </main>

      <div className="pt-16">
        <Footer locale={locale} />
      </div>
    </>
  );
}