"use client";

import { useState } from "react";
import { useCartStore } from "@/lib/store";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Separator } from "@/components/ui/separator";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { CreditCard, Truck, MapPin, CheckCircle } from "lucide-react";
import { toast } from "sonner";

const paymentMethods = [
  { id: "bkash", name: "bKash", icon: "📱", color: "bg-pink-500" },
  { id: "nagad", name: "Nagad", icon: "📱", color: "bg-orange-500" },
  { id: "rocket", name: "Rocket", icon: "📱", color: "bg-purple-500" },
  { id: "sslcommerz", name: "Card Payment", icon: "💳", color: "bg-blue-500" },
  { id: "cod", name: "Cash on Delivery", icon: "💵", color: "bg-green-500" },
];

interface CheckoutModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CheckoutModal({ open, onOpenChange }: CheckoutModalProps) {
  const { items, getTotalPrice, clearCart } = useCartStore();
  const { data: session } = useSession();
  const router = useRouter();
  
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [orderId, setOrderId] = useState<string | null>(null);
  
  const [formData, setFormData] = useState({
    name: session?.user?.name || "",
    phone: "",
    addressLine1: "",
    addressLine2: "",
    city: "",
    district: "",
    postalCode: "",
    notes: "",
    paymentMethod: "bkash",
    couponCode: "",
  });

  const total = getTotalPrice();
  const shippingCost = total > 1000 ? 0 : 60;
  const [discount, setDiscount] = useState(0);
  const grandTotal = total + shippingCost - discount;

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const applyCoupon = async () => {
    if (!formData.couponCode) return;
    
    try {
      const res = await fetch(`/api/coupons/validate?code=${formData.couponCode}`);
      const data = await res.json();
      
      if (data.valid) {
        const discountAmount = data.coupon.type === "percentage"
          ? (total * data.coupon.value) / 100
          : data.coupon.value;
        setDiscount(Math.min(discountAmount, data.coupon.maxDiscount || discountAmount));
        toast.success(`Coupon applied! You saved ৳${Math.min(discountAmount, data.coupon.maxDiscount || discountAmount).toFixed(0)}`);
      } else {
        toast.error("Invalid or expired coupon");
      }
    } catch (error) {
      toast.error("Failed to apply coupon");
    }
  };

  const handleSubmit = async () => {
    if (!session?.user?.id) {
      toast.error("Please login to checkout");
      router.push("/auth/signin");
      return;
    }

    setLoading(true);
    
    try {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items: items.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            attributes: item.attributes,
          })),
          shippingAddress: {
            name: formData.name,
            phone: formData.phone,
            addressLine1: formData.addressLine1,
            addressLine2: formData.addressLine2,
            city: formData.city,
            district: formData.district,
            postalCode: formData.postalCode,
          },
          paymentMethod: formData.paymentMethod,
          notes: formData.notes,
          couponCode: formData.couponCode || undefined,
        }),
      });

      const data = await res.json();

      if (res.ok) {
        setOrderId(data.id);
        setStep(3);
        clearCart();
        
        // Initiate payment if not COD
        if (formData.paymentMethod !== "cod") {
          const paymentRes = await fetch("/api/payment/initiate", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              orderId: data.id,
              method: formData.paymentMethod,
            }),
          });
          const paymentData = await paymentRes.json();
          
          if (paymentData.details) {
            toast.info(paymentData.details.instructions);
          }
        }
      } else {
        toast.error(data.error || "Failed to place order");
      }
    } catch (error) {
      toast.error("Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-2xl overflow-y-auto">
        <SheetHeader>
          <SheetTitle className="flex items-center gap-2">
            {step === 1 && <><MapPin className="h-5 w-5" /> Shipping Details</>}
            {step === 2 && <><CreditCard className="h-5 w-5" /> Payment Method</>}
            {step === 3 && <><CheckCircle className="h-5 w-5 text-green-500" /> Order Confirmed</>}
          </SheetTitle>
        </SheetHeader>

        <div className="mt-6">
          {/* Step 1: Shipping Details */}
          {step === 1 && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">Full Name</Label>
                  <Input
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    placeholder="Enter your name"
                  />
                </div>
                <div>
                  <Label htmlFor="phone">Phone Number</Label>
                  <Input
                    id="phone"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="01XXXXXXXXX"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="addressLine1">Address Line 1</Label>
                <Input
                  id="addressLine1"
                  name="addressLine1"
                  value={formData.addressLine1}
                  onChange={handleInputChange}
                  placeholder="House/Flat No, Street Name"
                />
              </div>

              <div>
                <Label htmlFor="addressLine2">Address Line 2 (Optional)</Label>
                <Input
                  id="addressLine2"
                  name="addressLine2"
                  value={formData.addressLine2}
                  onChange={handleInputChange}
                  placeholder="Area, Landmark"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="city">City</Label>
                  <Input
                    id="city"
                    name="city"
                    value={formData.city}
                    onChange={handleInputChange}
                    placeholder="City"
                  />
                </div>
                <div>
                  <Label htmlFor="district">District</Label>
                  <Input
                    id="district"
                    name="district"
                    value={formData.district}
                    onChange={handleInputChange}
                    placeholder="District"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="notes">Order Notes (Optional)</Label>
                <Input
                  id="notes"
                  name="notes"
                  value={formData.notes}
                  onChange={handleInputChange}
                  placeholder="Special instructions for delivery"
                />
              </div>

              <Button
                className="w-full"
                size="lg"
                onClick={() => setStep(2)}
                disabled={!formData.name || !formData.phone || !formData.addressLine1 || !formData.city || !formData.district}
              >
                Continue to Payment
              </Button>
            </div>
          )}

          {/* Step 2: Payment Method */}
          {step === 2 && (
            <div className="space-y-6">
              <div>
                <Label className="text-base font-medium">Select Payment Method</Label>
                <RadioGroup
                  value={formData.paymentMethod}
                  onValueChange={(value) => setFormData({ ...formData, paymentMethod: value })}
                  className="grid grid-cols-2 gap-3 mt-3"
                >
                  {paymentMethods.map((method) => (
                    <Label
                      key={method.id}
                      htmlFor={method.id}
                      className={`flex items-center gap-3 p-4 border rounded-lg cursor-pointer transition-all ${
                        formData.paymentMethod === method.id ? "border-primary bg-primary/5" : ""
                      }`}
                    >
                      <RadioGroupItem value={method.id} id={method.id} />
                      <span className="text-xl">{method.icon}</span>
                      <span className="font-medium">{method.name}</span>
                    </Label>
                  ))}
                </RadioGroup>
              </div>

              {/* Coupon Code */}
              <div>
                <Label htmlFor="couponCode">Coupon Code</Label>
                <div className="flex gap-2 mt-1">
                  <Input
                    id="couponCode"
                    name="couponCode"
                    value={formData.couponCode}
                    onChange={handleInputChange}
                    placeholder="Enter coupon code"
                  />
                  <Button variant="outline" onClick={applyCoupon}>Apply</Button>
                </div>
              </div>

              {/* Order Summary */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Order Summary</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex justify-between">
                    <span>Subtotal ({items.length} items)</span>
                    <span>৳{total.toLocaleString()}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Shipping</span>
                    <span>{shippingCost === 0 ? "Free" : `৳${shippingCost}`}</span>
                  </div>
                  {discount > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>Discount</span>
                      <span>-৳{discount.toFixed(0)}</span>
                    </div>
                  )}
                  <Separator />
                  <div className="flex justify-between font-bold text-lg">
                    <span>Total</span>
                    <span>৳{grandTotal.toLocaleString()}</span>
                  </div>
                </CardContent>
              </Card>

              <div className="flex gap-3">
                <Button variant="outline" onClick={() => setStep(1)} className="flex-1">
                  Back
                </Button>
                <Button
                  className="flex-1"
                  size="lg"
                  onClick={handleSubmit}
                  disabled={loading}
                >
                  {loading ? "Processing..." : `Pay ৳${grandTotal.toLocaleString()}`}
                </Button>
              </div>
            </div>
          )}

          {/* Step 3: Order Confirmed */}
          {step === 3 && (
            <div className="text-center py-8">
              <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-12 h-12 text-green-500" />
              </div>
              <h2 className="text-2xl font-bold mb-2">Order Placed Successfully!</h2>
              <p className="text-muted-foreground mb-4">
                Your order has been placed. We will contact you shortly.
              </p>
              {orderId && (
                <p className="text-sm text-muted-foreground mb-6">
                  Order ID: {orderId}
                </p>
              )}
              <div className="flex gap-3 justify-center">
                <Button variant="outline" onClick={() => onOpenChange(false)}>
                  Continue Shopping
                </Button>
                <Button onClick={() => router.push("/orders")}>
                  View Orders
                </Button>
              </div>
            </div>
          )}
        </div>
      </SheetContent>
    </Sheet>
  );
}
