"use client"

import type React from "react"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { motion } from "framer-motion"
import { Search, Package, Truck, CheckCircle, Clock, AlertCircle } from "lucide-react"

export default function OrderTrackingPage() {
  const [orderNumber, setOrderNumber] = useState("")
  const [email, setEmail] = useState("")
  const [isTracking, setIsTracking] = useState(false)
  const [orderFound, setOrderFound] = useState(false)

  // Mock order data
  const orderData = {
    id: "ORD-12345",
    date: "15.03.2025",
    status: "В пути",
    statusCode: "in_transit", // possible values: processing, in_transit, delivered, cancelled
    estimatedDelivery: "18.03.2025",
    items: [
      {
        id: 1,
        name: "Платье с цветочным принтом",
        price: 5990,
        quantity: 1,
        image: "/placeholder.svg?height=600&width=400",
      },
      {
        id: 2,
        name: "Блуза из натурального шелка",
        price: 4990,
        quantity: 2,
        image: "/placeholder.svg?height=600&width=400",
      },
    ],
    shipping: {
      method: "Курьерская доставка",
      address: "ул. Ленина, 123, кв. 45, Москва, 123456",
      cost: 500,
    },
    payment: {
      method: "Банковская карта",
      total: 16470,
    },
    trackingSteps: [
      {
        id: 1,
        title: "Заказ оформлен",
        date: "15.03.2025, 10:23",
        completed: true,
      },
      {
        id: 2,
        title: "Заказ подтвержден",
        date: "15.03.2025, 11:45",
        completed: true,
      },
      {
        id: 3,
        title: "Заказ передан в доставку",
        date: "16.03.2025, 09:30",
        completed: true,
      },
      {
        id: 4,
        title: "Заказ в пути",
        date: "16.03.2025, 14:15",
        completed: true,
        current: true,
      },
      {
        id: 5,
        title: "Заказ доставлен",
        date: "",
        completed: false,
      },
    ],
  }

  const handleTrackOrder = (e: React.FormEvent) => {
    e.preventDefault()
    setIsTracking(true)

    // Simulate API call
    setTimeout(() => {
      // For demo purposes, we'll show the order if the order number matches
      if (orderNumber === "ORD-12345") {
        setOrderFound(true)
      } else {
        setOrderFound(false)
      }
    }, 1000)
  }

  const getStatusColor = (statusCode: string) => {
    switch (statusCode) {
      case "processing":
        return "bg-blue-100 text-blue-800"
      case "in_transit":
        return "bg-yellow-100 text-yellow-800"
      case "delivered":
        return "bg-green-100 text-green-800"
      case "cancelled":
        return "bg-red-100 text-red-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  const getStatusIcon = (statusCode: string) => {
    switch (statusCode) {
      case "processing":
        return <Clock className="h-5 w-5 mr-2" />
      case "in_transit":
        return <Truck className="h-5 w-5 mr-2" />
      case "delivered":
        return <CheckCircle className="h-5 w-5 mr-2" />
      case "cancelled":
        return <AlertCircle className="h-5 w-5 mr-2" />
      default:
        return <Package className="h-5 w-5 mr-2" />
    }
  }

  return (
    <div className="bg-white">
      {/* Hero Section */}
      <section className="relative h-[40vh] min-h-[300px] bg-gray-100">
        <div
          className="absolute inset-0 bg-cover bg-center"
          style={{ backgroundImage: "url('/placeholder.svg?height=800&width=1920')" }}
        >
          <div className="absolute inset-0 bg-gradient-to-r from-primary/80 to-primary/40"></div>
        </div>

        <div className="relative h-full container mx-auto px-4 flex flex-col justify-center">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            className="max-w-2xl text-white"
          >
            <h1 className="text-4xl md:text-5xl font-bold mb-4">Отслеживание заказа</h1>
            <p className="text-xl opacity-90">Узнайте, где находится ваш заказ и когда он будет доставлен</p>
          </motion.div>
        </div>
      </section>

      <section className="py-20">
        <div className="container mx-auto px-4">
          <div className="max-w-3xl mx-auto">
            {/* Tracking Form */}
            <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 mb-12">
              <h2 className="text-2xl font-bold text-primary mb-6">Введите данные для отслеживания</h2>

              <form onSubmit={handleTrackOrder} className="space-y-6">
                <div className="space-y-2">
                  <label htmlFor="orderNumber" className="block font-medium">
                    Номер заказа
                  </label>
                  <div className="relative">
                    <Package className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" />
                    <Input
                      id="orderNumber"
                      placeholder="Например, ORD-12345"
                      className="pl-10 border-gray-300"
                      value={orderNumber}
                      onChange={(e) => setOrderNumber(e.target.value)}
                      required
                    />
                  </div>
                  <p className="text-sm text-gray-500">Номер заказа указан в письме с подтверждением заказа</p>
                </div>

                <div className="space-y-2">
                  <label htmlFor="email" className="block font-medium">
                    Email
                  </label>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="Введите email, указанный при оформлении заказа"
                      className="pl-10 border-gray-300"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>
                </div>

                <Button type="submit" className="bg-primary hover:bg-secondary rounded-full px-8 py-6 w-full md:w-auto">
                  Отследить заказ
                </Button>
              </form>
            </div>

            {/* Tracking Results */}
            {isTracking && (
              <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}>
                {orderFound ? (
                  <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100">
                    <div className="flex justify-between items-start mb-8 flex-wrap gap-4">
                      <div>
                        <h2 className="text-2xl font-bold text-primary mb-2">Заказ {orderData.id}</h2>
                        <p className="text-gray-600">от {orderData.date}</p>
                      </div>

                      <div className="flex items-center">
                        <div
                          className={`px-4 py-2 rounded-full flex items-center ${getStatusColor(orderData.statusCode)}`}
                        >
                          {getStatusIcon(orderData.statusCode)}
                          <span>{orderData.status}</span>
                        </div>
                      </div>
                    </div>

                    {/* Tracking Progress */}
                    <div className="mb-12">
                      <h3 className="text-lg font-bold text-gray-800 mb-6">Статус доставки</h3>

                      <div className="relative">
                        {/* Progress Line */}
                        <div className="absolute left-6 top-0 bottom-0 w-0.5 bg-gray-200"></div>

                        {/* Steps */}
                        <div className="space-y-8">
                          {orderData.trackingSteps.map((step) => (
                            <div key={step.id} className="relative flex items-start">
                              <div
                                className={`relative z-10 flex items-center justify-center w-12 h-12 rounded-full mr-4 ${
                                  step.completed
                                    ? step.current
                                      ? "bg-primary text-white"
                                      : "bg-tertiary text-primary"
                                    : "bg-gray-100 text-gray-400"
                                }`}
                              >
                                {step.completed ? (
                                  step.current ? (
                                    <Truck className="h-6 w-6" />
                                  ) : (
                                    <CheckCircle className="h-6 w-6" />
                                  )
                                ) : (
                                  <span className="text-lg font-bold">{step.id}</span>
                                )}
                              </div>

                              <div>
                                <h4 className={`font-bold ${step.current ? "text-primary" : "text-gray-800"}`}>
                                  {step.title}
                                </h4>
                                <p className="text-gray-600">{step.date || "Ожидается"}</p>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div className="mt-6 p-4 bg-tertiary/30 rounded-lg">
                        <p className="flex items-center text-primary">
                          <Clock className="h-5 w-5 mr-2" />
                          Ожидаемая дата доставки: <span className="font-bold ml-1">{orderData.estimatedDelivery}</span>
                        </p>
                      </div>
                    </div>

                    {/* Order Details */}
                    <div className="mb-8">
                      <h3 className="text-lg font-bold text-gray-800 mb-4">Детали заказа</h3>

                      <div className="space-y-4">
                        {orderData.items.map((item) => (
                          <div key={item.id} className="flex gap-4 p-4 border border-gray-100 rounded-lg">
                            <div className="relative w-16 h-16 flex-shrink-0">
                              <Image
                                src={item.image || "/placeholder.svg"}
                                alt={item.name}
                                fill
                                className="object-cover rounded-md"
                              />
                            </div>

                            <div className="flex-1">
                              <h4 className="font-medium">{item.name}</h4>
                              <p className="text-sm text-gray-600">Количество: {item.quantity}</p>
                              <p className="text-sm font-bold text-primary">
                                {(item.price * item.quantity).toLocaleString()} ₽
                              </p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Shipping and Payment */}
                    <div className="grid md:grid-cols-2 gap-8">
                      <div>
                        <h3 className="text-lg font-bold text-gray-800 mb-4">Информация о доставке</h3>
                        <div className="p-4 border border-gray-100 rounded-lg">
                          <p className="font-medium mb-2">{orderData.shipping.method}</p>
                          <p className="text-gray-600 mb-4">{orderData.shipping.address}</p>
                          <p className="text-sm">
                            Стоимость доставки:{" "}
                            <span className="font-bold">{orderData.shipping.cost.toLocaleString()} ₽</span>
                          </p>
                        </div>
                      </div>

                      <div>
                        <h3 className="text-lg font-bold text-gray-800 mb-4">Информация об оплате</h3>
                        <div className="p-4 border border-gray-100 rounded-lg">
                          <p className="font-medium mb-4">{orderData.payment.method}</p>
                          <p className="text-sm">
                            Итого:{" "}
                            <span className="font-bold text-lg text-primary">
                              {orderData.payment.total.toLocaleString()} ₽
                            </span>
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="mt-8 flex flex-wrap gap-4">
                      <Button asChild className="bg-primary hover:bg-secondary rounded-full">
                        <Link href="/contact">Связаться с нами</Link>
                      </Button>
                      <Button
                        asChild
                        variant="outline"
                        className="border-primary text-primary hover:bg-primary hover:text-white rounded-full"
                      >
                        <Link href="/account/orders">Все мои заказы</Link>
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 text-center">
                    <div className="inline-flex items-center justify-center w-20 h-20 bg-red-100 rounded-full mb-6">
                      <AlertCircle className="h-10 w-10 text-red-500" />
                    </div>
                    <h2 className="text-2xl font-bold text-gray-800 mb-4">Заказ не найден</h2>
                    <p className="text-gray-600 mb-6">
                      К сожалению, мы не смогли найти заказ с номером <strong>{orderNumber}</strong>. Пожалуйста,
                      проверьте правильность введенных данных и попробуйте снова.
                    </p>
                    <Button
                      className="bg-primary hover:bg-secondary rounded-full px-8"
                      onClick={() => setIsTracking(false)}
                    >
                      Попробовать снова
                    </Button>
                  </div>
                )}
              </motion.div>
            )}

            {/* Help Section */}
            {!isTracking && (
              <div className="mt-16 bg-tertiary/30 p-8 rounded-2xl">
                <h3 className="text-xl font-bold text-primary mb-4">Нужна помощь?</h3>
                <p className="text-gray-700 mb-6">
                  Если у вас возникли вопросы по отслеживанию заказа или вы не можете найти номер заказа, свяжитесь с
                  нашей службой поддержки клиентов.
                </p>
                <Button asChild className="bg-primary hover:bg-secondary rounded-full">
                  <Link href="/contact">Связаться с нами</Link>
                </Button>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  )
}

