"use client";

import React, { useState, useEffect } from "react";
import { Check, X, Phone, MapPin, Package, Clock, AlertCircle } from "lucide-react";
import { DashboardElement } from "@/components/admin/dashboard/types";

interface BookingRequest {
  id: string;
  customerName: string;
  customerPhone: string;
  pickupLocation: string;
  dropoffLocation: string;
  scheduledTime: string;
  vehicleType: "truck" | "van" | "car";
  cargoType?: string;
  weight?: number;
  status: "pending" | "accepted" | "rejected" | "completed";
  priority: "normal" | "urgent";
  createdAt: string;
  estimatedCost?: number;
}

interface BookingAlertWidgetProps {
  element?: DashboardElement;
}

export default function BookingAlertWidget({ element }: BookingAlertWidgetProps) {
  const [bookings, setBookings] = useState<BookingRequest[]>([]);
  const [newCount, setNewCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<"all" | "pending" | "accepted">("pending");
  const [showNotification, setShowNotification] = useState(false);

  useEffect(() => {
    fetchBookings();
    const interval = setInterval(fetchBookings, 10000); // 10초마다 갱신
    return () => clearInterval(interval);
  }, [filter]);

  const fetchBookings = async () => {
    try {
      const token = localStorage.getItem("authToken");
      const filterParam = filter !== "all" ? `?status=${filter}` : "";
      const response = await fetch(`http://localhost:9771/api/bookings${filterParam}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const result = await response.json();
        const newBookings = result.data || [];
        
        // 신규 예약이 있으면 알림 표시
        if (result.newCount > 0 && newBookings.length > bookings.length) {
          setShowNotification(true);
          setTimeout(() => setShowNotification(false), 5000);
        }
        
        setBookings(newBookings);
        setNewCount(result.newCount);
      }
    } catch (error) {
      // console.error("예약 로딩 오류:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleAccept = async (id: string) => {
    if (!confirm("이 예약을 수락하시겠습니까?")) return;

    try {
      const token = localStorage.getItem("authToken");
      const response = await fetch(`http://localhost:9771/api/bookings/${id}/accept`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        fetchBookings();
      }
    } catch (error) {
      // console.error("예약 수락 오류:", error);
    }
  };

  const handleReject = async (id: string) => {
    const reason = prompt("거절 사유를 입력하세요:");
    if (!reason) return;

    try {
      const token = localStorage.getItem("authToken");
      const response = await fetch(`http://localhost:9771/api/bookings/${id}/reject`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ reason }),
      });

      if (response.ok) {
        fetchBookings();
      }
    } catch (error) {
      // console.error("예약 거절 오류:", error);
    }
  };

  const getVehicleIcon = (type: string) => {
    switch (type) {
      case "truck":
        return "🚚";
      case "van":
        return "🚐";
      case "car":
        return "🚗";
      default:
        return "🚗";
    }
  };

  const getTimeStatus = (scheduledTime: string) => {
    const now = new Date();
    const scheduled = new Date(scheduledTime);
    const diff = scheduled.getTime() - now.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));

    if (hours < 0) return { text: "⏰ 시간 초과", color: "text-red-600" };
    if (hours < 2) return { text: `⏱️ ${hours}시간 후`, color: "text-red-600" };
    if (hours < 4) return { text: `⏱️ ${hours}시간 후`, color: "text-orange-600" };
    return { text: `📅 ${hours}시간 후`, color: "text-gray-600" };
  };

  const isNew = (createdAt: string) => {
    const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
    return new Date(createdAt) > fiveMinutesAgo;
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-gray-500">로딩 중...</div>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-rose-50">
      {/* 신규 알림 배너 */}
      {showNotification && newCount > 0 && (
        <div className="animate-pulse border-b border-rose-300 bg-rose-100 px-4 py-2 text-center">
          <span className="font-bold text-rose-700">🔔 새로운 예약 {newCount}건이 도착했습니다!</span>
        </div>
      )}

      {/* 헤더 */}
      <div className="border-b border-gray-200 bg-white px-4 py-3">
        <div className="mb-3 flex items-center justify-between">
          <div className="flex items-center gap-2">
              <h3 className="text-lg font-bold text-gray-800">{element?.customTitle || "예약 요청 알림"}</h3>
            {newCount > 0 && (
              <span className="flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white">
                {newCount}
              </span>
            )}
          </div>
          <button
            onClick={fetchBookings}
            className="rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
          >
            🔄 새로고침
          </button>
        </div>

        {/* 필터 */}
        <div className="flex gap-2">
          {(["pending", "accepted", "all"] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
                filter === f ? "bg-primary text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              {f === "pending" ? "대기중" : f === "accepted" ? "수락됨" : "전체"}
            </button>
          ))}
        </div>
      </div>

      {/* 예약 리스트 */}
      <div className="flex-1 overflow-y-auto p-4">
        {bookings.length === 0 ? (
          <div className="flex h-full items-center justify-center text-gray-400">
            <div className="text-center">
              <div className="mb-2 text-4xl">📭</div>
              <div>예약 요청이 없습니다</div>
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {bookings.map((booking) => (
              <div
                key={booking.id}
                className={`group relative rounded-lg border-2 bg-white p-4 shadow-sm transition-all hover:shadow-md ${
                  booking.priority === "urgent" ? "border-red-400" : "border-gray-200"
                } ${booking.status !== "pending" ? "opacity-60" : ""}`}
              >
                {/* NEW 뱃지 */}
                {isNew(booking.createdAt) && booking.status === "pending" && (
                  <div className="absolute -right-2 -top-2 animate-bounce">
                    <span className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white shadow-lg">
                      🆕
                    </span>
                  </div>
                )}

                {/* 우선순위 표시 */}
                {booking.priority === "urgent" && (
                  <div className="mb-2 flex items-center gap-1 text-sm font-bold text-red-600">
                    <AlertCircle className="h-4 w-4" />
                    긴급 예약
                  </div>
                )}

                {/* 고객 정보 */}
                <div className="mb-3 flex items-start justify-between">
                  <div className="flex-1">
                    <div className="mb-1 flex items-center gap-2">
                      <span className="text-2xl">{getVehicleIcon(booking.vehicleType)}</span>
                      <div>
                        <div className="font-bold text-gray-800">{booking.customerName}</div>
                        <div className="flex items-center gap-1 text-xs text-gray-600">
                          <Phone className="h-3 w-3" />
                          {booking.customerPhone}
                        </div>
                      </div>
                    </div>
                  </div>
                  {booking.status === "pending" && (
                    <div className="flex gap-1">
                      <button
                        onClick={() => handleAccept(booking.id)}
                        className="flex items-center gap-1 rounded bg-green-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-green-600"
                      >
                        <Check className="h-4 w-4" />
                        수락
                      </button>
                      <button
                        onClick={() => handleReject(booking.id)}
                        className="flex items-center gap-1 rounded bg-red-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-red-600"
                      >
                        <X className="h-4 w-4" />
                        거절
                      </button>
                    </div>
                  )}
                  {booking.status === "accepted" && (
                    <span className="rounded bg-green-100 px-2 py-1 text-xs font-medium text-green-700">
                      ✓ 수락됨
                    </span>
                  )}
                </div>

                {/* 경로 정보 */}
                <div className="mb-3 space-y-2 border-t border-gray-100 pt-3">
                  <div className="flex items-start gap-2 text-sm">
                    <MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-blue-600" />
                    <div className="flex-1">
                      <div className="font-medium text-gray-700">출발지</div>
                      <div className="text-gray-600">{booking.pickupLocation}</div>
                    </div>
                  </div>
                  <div className="flex items-start gap-2 text-sm">
                    <MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-rose-600" />
                    <div className="flex-1">
                      <div className="font-medium text-gray-700">도착지</div>
                      <div className="text-gray-600">{booking.dropoffLocation}</div>
                    </div>
                  </div>
                </div>

                {/* 상세 정보 */}
                <div className="grid grid-cols-2 gap-2 text-xs">
                  <div className="flex items-center gap-1">
                    <Package className="h-3 w-3 text-gray-500" />
                    <span className="text-gray-600">
                      {booking.cargoType} ({booking.weight}kg)
                    </span>
                  </div>
                  <div className={`flex items-center gap-1 ${getTimeStatus(booking.scheduledTime).color}`}>
                    <Clock className="h-3 w-3" />
                    <span className="font-medium">{getTimeStatus(booking.scheduledTime).text}</span>
                  </div>
                  {booking.estimatedCost && (
                    <div className="col-span-2 font-bold text-primary">
                      예상 비용: {booking.estimatedCost.toLocaleString()}원
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

