"use client"

import type React from "react"

import { useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import Link from "next/link"
import { ArrowLeft, Banknote, CreditCard, Building2, Smartphone, Check, Package } from "lucide-react"
import { Header } from "@/components/header"
import { Footer } from "@/components/footer"
import { CartProvider, useCart } from "@/lib/cart-context"
import { AdminProvider, useAdmin } from "@/lib/admin-context"

type PaymentMethod = "cod" | "easypaisa" | "jazzcash" | "bank"

function CheckoutContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const paymentType = searchParams.get("type") as "cod" | "online" | null
  const { items, totalPrice, clearCart } = useCart()
  const { paymentSettings, addOrder } = useAdmin()

  const [step, setStep] = useState<"payment-select" | "form">(paymentType === "cod" ? "form" : "payment-select")
  const [selectedPayment, setSelectedPayment] = useState<PaymentMethod>(paymentType === "cod" ? "cod" : "easypaisa")

  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    houseNumber: "",
    street: "",
    colony: "",
    city: "",
    postalCode: "",
    additionalNotes: "",
  })

  const [errors, setErrors] = useState<Record<string, string>>({})

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }))
    }
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}
    if (!formData.name.trim()) newErrors.name = "Name is required"
    if (!formData.phone.trim()) newErrors.phone = "Phone number is required"
    else if (!/^0[0-9]{10}$/.test(formData.phone.replace(/-/g, "")))
      newErrors.phone = "Enter valid Pakistani phone number"
    if (!formData.houseNumber.trim()) newErrors.houseNumber = "House/Building number is required"
    if (!formData.street.trim()) newErrors.street = "Street name is required"
    if (!formData.colony.trim()) newErrors.colony = "Colony/Area is required"
    if (!formData.city.trim()) newErrors.city = "City is required"
    if (!formData.postalCode.trim()) newErrors.postalCode = "Postal code is required"
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) return

    const orderId = addOrder({
      customerName: formData.name,
      phone: formData.phone,
      houseNumber: formData.houseNumber,
      street: formData.street,
      colony: formData.colony,
      city: formData.city,
      postalCode: formData.postalCode,
      additionalNotes: formData.additionalNotes,
      items: items.map((item) => ({
        productId: item.id,
        productName: item.name,
        quantity: item.quantity,
        price: item.price,
      })),
      total: totalPrice,
      paymentMethod: selectedPayment,
      paymentStatus: selectedPayment === "cod" ? "pending" : "pending",
      status: "pending",
    })

    clearCart()
    router.push(`/checkout/thank-you?orderId=${orderId}&payment=${selectedPayment}`)
  }

  if (items.length === 0) {
    return (
      <div className="container mx-auto px-4 py-16 text-center">
        <Package className="w-20 h-20 text-muted-foreground mx-auto mb-6" />
        <h2 className="text-2xl font-bold text-foreground mb-4">Your Cart is Empty</h2>
        <p className="text-muted-foreground mb-8">Add products to your cart before checkout.</p>
        <Link
          href="/"
          className="inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-primary-foreground px-6 py-3 rounded-lg font-semibold"
        >
          <ArrowLeft className="w-5 h-5" />
          Continue Shopping
        </Link>
      </div>
    )
  }

  const paymentOptions = [
    {
      id: "easypaisa" as const,
      name: "EasyPaisa",
      icon: Smartphone,
      color: "bg-green-500",
      number: paymentSettings.easypaisaNumber,
    },
    {
      id: "jazzcash" as const,
      name: "JazzCash",
      icon: Smartphone,
      color: "bg-red-500",
      number: paymentSettings.jazzcashNumber,
    },
    {
      id: "bank" as const,
      name: "Bank Transfer",
      icon: Building2,
      color: "bg-blue-500",
      details: {
        bankName: paymentSettings.bankName,
        accountTitle: paymentSettings.accountTitle,
        accountNumber: paymentSettings.accountNumber,
      },
    },
  ]

  return (
    <div className="container mx-auto px-4 py-8">
      <Link href="/cart" className="inline-flex items-center gap-2 text-primary hover:text-primary/80 font-medium mb-6">
        <ArrowLeft className="w-5 h-5" />
        Back to Cart
      </Link>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <div className="lg:col-span-2">
          {/* Payment Method Selection (for online payments) */}
          {paymentType === "online" && step === "payment-select" && (
            <div className="bg-card rounded-xl border border-border p-6 mb-6">
              <h2 className="text-xl font-bold text-foreground mb-6 flex items-center gap-2">
                <CreditCard className="w-6 h-6 text-primary" />
                Select Payment Method
              </h2>

              <div className="space-y-4">
                {paymentOptions.map((option) => (
                  <button
                    key={option.id}
                    onClick={() => setSelectedPayment(option.id)}
                    className={`w-full p-4 rounded-xl border-2 transition-all text-left ${
                      selectedPayment === option.id
                        ? "border-primary bg-primary/5"
                        : "border-border hover:border-primary/50"
                    }`}
                  >
                    <div className="flex items-center gap-4">
                      <div className={`w-12 h-12 ${option.color} rounded-xl flex items-center justify-center`}>
                        <option.icon className="w-6 h-6 text-white" />
                      </div>
                      <div className="flex-1">
                        <h3 className="font-semibold text-foreground">{option.name}</h3>
                        {option.number && <p className="text-sm text-muted-foreground">{option.number}</p>}
                        {option.details && (
                          <p className="text-sm text-muted-foreground">
                            {option.details.bankName} - {option.details.accountTitle}
                          </p>
                        )}
                      </div>
                      {selectedPayment === option.id && (
                        <div className="w-6 h-6 rounded-full bg-primary flex items-center justify-center">
                          <Check className="w-4 h-4 text-primary-foreground" />
                        </div>
                      )}
                    </div>
                  </button>
                ))}
              </div>

              {/* Payment Instructions */}
              {selectedPayment && selectedPayment !== "cod" && (
                <div className="mt-6 p-4 bg-amber-50 border border-amber-200 rounded-xl">
                  <h4 className="font-semibold text-amber-800 mb-2">Payment Instructions</h4>
                  {selectedPayment === "easypaisa" && (
                    <div className="text-sm text-amber-700 space-y-1">
                      <p>1. Open EasyPaisa App or dial *786#</p>
                      <p>
                        2. Send <strong>Rs. {totalPrice.toLocaleString()}</strong> to:
                      </p>
                      <p className="font-bold text-lg text-amber-900">{paymentSettings.easypaisaNumber}</p>
                      <p>3. Save the transaction ID for confirmation</p>
                    </div>
                  )}
                  {selectedPayment === "jazzcash" && (
                    <div className="text-sm text-amber-700 space-y-1">
                      <p>1. Open JazzCash App or dial *786#</p>
                      <p>
                        2. Send <strong>Rs. {totalPrice.toLocaleString()}</strong> to:
                      </p>
                      <p className="font-bold text-lg text-amber-900">{paymentSettings.jazzcashNumber}</p>
                      <p>3. Save the transaction ID for confirmation</p>
                    </div>
                  )}
                  {selectedPayment === "bank" && (
                    <div className="text-sm text-amber-700 space-y-1">
                      <p>
                        Transfer <strong>Rs. {totalPrice.toLocaleString()}</strong> to:
                      </p>
                      <p>
                        <strong>Bank:</strong> {paymentSettings.bankName}
                      </p>
                      <p>
                        <strong>Account Title:</strong> {paymentSettings.accountTitle}
                      </p>
                      <p>
                        <strong>IBAN/Account:</strong>{" "}
                        <span className="font-mono">{paymentSettings.accountNumber}</span>
                      </p>
                      <p className="mt-2">Save the transaction receipt for confirmation</p>
                    </div>
                  )}
                </div>
              )}

              <button
                onClick={() => setStep("form")}
                className="w-full mt-6 bg-primary hover:bg-primary/90 text-primary-foreground py-4 rounded-xl font-semibold text-lg transition-colors"
              >
                Continue to Delivery Address
              </button>
            </div>
          )}

          {/* Delivery Address Form */}
          {(paymentType === "cod" || step === "form") && (
            <form onSubmit={handleSubmit} className="bg-card rounded-xl border border-border p-6">
              <h2 className="text-xl font-bold text-foreground mb-6 flex items-center gap-2">
                {paymentType === "cod" ? (
                  <>
                    <Banknote className="w-6 h-6 text-primary" />
                    Cash on Delivery
                  </>
                ) : (
                  "Delivery Address"
                )}
              </h2>

              {paymentType === "cod" && (
                <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-xl">
                  <p className="text-green-800 text-sm">
                    Pay <strong>Rs. {totalPrice.toLocaleString()}</strong> in cash when your order arrives. No advance
                    payment required.
                  </p>
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground mb-1">Full Name *</label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    placeholder="Enter your full name"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.name ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.name && <p className="text-destructive text-xs mt-1">{errors.name}</p>}
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground mb-1">Phone Number *</label>
                  <input
                    type="tel"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="03XX-XXXXXXX"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.phone ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.phone && <p className="text-destructive text-xs mt-1">{errors.phone}</p>}
                </div>

                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">House/Building No. *</label>
                  <input
                    type="text"
                    name="houseNumber"
                    value={formData.houseNumber}
                    onChange={handleInputChange}
                    placeholder="House #, Flat #, Building"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.houseNumber ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.houseNumber && <p className="text-destructive text-xs mt-1">{errors.houseNumber}</p>}
                </div>

                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">Street *</label>
                  <input
                    type="text"
                    name="street"
                    value={formData.street}
                    onChange={handleInputChange}
                    placeholder="Street name"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.street ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.street && <p className="text-destructive text-xs mt-1">{errors.street}</p>}
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground mb-1">Colony/Area *</label>
                  <input
                    type="text"
                    name="colony"
                    value={formData.colony}
                    onChange={handleInputChange}
                    placeholder="Colony, Sector, or Area"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.colony ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.colony && <p className="text-destructive text-xs mt-1">{errors.colony}</p>}
                </div>

                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">City *</label>
                  <select
                    name="city"
                    value={formData.city}
                    onChange={handleInputChange}
                    className={`w-full px-4 py-3 rounded-lg border ${errors.city ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  >
                    <option value="">Select City</option>
                    <option value="Karachi">Karachi</option>
                    <option value="Lahore">Lahore</option>
                    <option value="Islamabad">Islamabad</option>
                    <option value="Rawalpindi">Rawalpindi</option>
                    <option value="Faisalabad">Faisalabad</option>
                    <option value="Multan">Multan</option>
                    <option value="Peshawar">Peshawar</option>
                    <option value="Quetta">Quetta</option>
                    <option value="Sialkot">Sialkot</option>
                    <option value="Gujranwala">Gujranwala</option>
                    <option value="Other">Other</option>
                  </select>
                  {errors.city && <p className="text-destructive text-xs mt-1">{errors.city}</p>}
                </div>

                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">Postal Code *</label>
                  <input
                    type="text"
                    name="postalCode"
                    value={formData.postalCode}
                    onChange={handleInputChange}
                    placeholder="e.g., 54000"
                    className={`w-full px-4 py-3 rounded-lg border ${errors.postalCode ? "border-destructive" : "border-border"} bg-background text-foreground`}
                  />
                  {errors.postalCode && <p className="text-destructive text-xs mt-1">{errors.postalCode}</p>}
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground mb-1">Additional Notes (Optional)</label>
                  <textarea
                    name="additionalNotes"
                    value={formData.additionalNotes}
                    onChange={handleInputChange}
                    placeholder="Any special instructions for delivery..."
                    rows={3}
                    className="w-full px-4 py-3 rounded-lg border border-border bg-background text-foreground resize-none"
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full mt-6 bg-primary hover:bg-primary/90 text-primary-foreground py-4 rounded-xl font-semibold text-lg transition-colors"
              >
                {paymentType === "cod" ? "Place Order (Cash on Delivery)" : "Confirm Order"}
              </button>
            </form>
          )}
        </div>

        {/* Order Summary Sidebar */}
        <div className="lg:col-span-1">
          <div className="bg-card rounded-xl border border-border p-6 sticky top-24">
            <h2 className="text-xl font-bold text-foreground mb-4">Order Summary</h2>

            <div className="space-y-3 mb-4 max-h-60 overflow-y-auto">
              {items.map((item) => (
                <div key={item.id} className="flex gap-3">
                  <img
                    src={item.image || "/placeholder.svg"}
                    alt={item.name}
                    className="w-14 h-14 object-cover rounded-lg"
                  />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground line-clamp-1">{item.name}</p>
                    <p className="text-xs text-muted-foreground">Qty: {item.quantity}</p>
                    <p className="text-sm font-semibold text-success">
                      Rs. {(item.price * item.quantity).toLocaleString()}
                    </p>
                  </div>
                </div>
              ))}
            </div>

            <div className="border-t border-border pt-4 space-y-2">
              <div className="flex justify-between text-muted-foreground">
                <span>Subtotal</span>
                <span>Rs. {totalPrice.toLocaleString()}</span>
              </div>
              <div className="flex justify-between text-muted-foreground">
                <span>Delivery</span>
                <span className="text-success">Free</span>
              </div>
              <div className="flex justify-between font-bold text-lg text-foreground pt-2 border-t border-border">
                <span>Total</span>
                <span>Rs. {totalPrice.toLocaleString()}</span>
              </div>
            </div>

            <div className="mt-4 p-3 bg-muted rounded-lg">
              <p className="text-xs text-muted-foreground text-center">100% Private & Discreet Packaging Guaranteed</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default function CheckoutPage() {
  return (
    <CartProvider>
      <AdminProvider>
        <div className="min-h-screen flex flex-col">
          <Header />
          <main className="flex-1 bg-muted">
            <CheckoutContent />
          </main>
          <Footer />
        </div>
      </AdminProvider>
    </CartProvider>
  )
}
