"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-destructive" };
    if (hours < 2) return { text: `⏱️ ${hours}시간 후`, color: "text-destructive" };
    if (hours < 4) return { text: `⏱️ ${hours}시간 후`, color: "text-warning" };
    return { text: `📅 ${hours}시간 후`, color: "text-foreground" };
  };

  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-muted-foreground">로딩 중...</div>
      </div>
    );
  }

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

      {/* 헤더 */}
      <div className="border-b border-border bg-background 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-foreground">{element?.customTitle || "예약 요청 알림"}</h3>
            {newCount > 0 && (
              <span className="flex h-6 w-6 items-center justify-center rounded-full bg-destructive text-xs font-bold text-primary-foreground">
                {newCount}
              </span>
            )}
          </div>
          <button
            onClick={fetchBookings}
            className="rounded-lg bg-primary px-3 py-1.5 text-sm text-primary-foreground 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-primary-foreground" : "bg-muted text-foreground hover:bg-muted"
              }`}
            >
              {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-muted-foreground">
            <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-background p-4 shadow-sm transition-all hover:shadow-md ${
                  booking.priority === "urgent" ? "border-destructive" : "border-border"
                } ${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-destructive text-xs font-bold text-primary-foreground shadow-lg">
                      🆕
                    </span>
                  </div>
                )}

                {/* 우선순위 표시 */}
                {booking.priority === "urgent" && (
                  <div className="mb-2 flex items-center gap-1 text-sm font-bold text-destructive">
                    <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-foreground">{booking.customerName}</div>
                        <div className="flex items-center gap-1 text-xs text-foreground">
                          <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-success px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-success/90"
                      >
                        <Check className="h-4 w-4" />
                        수락
                      </button>
                      <button
                        onClick={() => handleReject(booking.id)}
                        className="flex items-center gap-1 rounded bg-destructive px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-destructive/90"
                      >
                        <X className="h-4 w-4" />
                        거절
                      </button>
                    </div>
                  )}
                  {booking.status === "accepted" && (
                    <span className="rounded bg-success/10 px-2 py-1 text-xs font-medium text-success">
                      ✓ 수락됨
                    </span>
                  )}
                </div>

                {/* 경로 정보 */}
                <div className="mb-3 space-y-2 border-t border-border pt-3">
                  <div className="flex items-start gap-2 text-sm">
                    <MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-primary" />
                    <div className="flex-1">
                      <div className="font-medium text-foreground">출발지</div>
                      <div className="text-foreground">{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-destructive" />
                    <div className="flex-1">
                      <div className="font-medium text-foreground">도착지</div>
                      <div className="text-foreground">{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-muted-foreground" />
                    <span className="text-foreground">
                      {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>
  );
}

