import React from "react";
import { Link } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { MapPin, Users, Calendar, Clock } from "lucide-react";
import { format, differenceInHours, parseISO } from "date-fns";

function UpcomingOrderItem({ order }) {
  const assignedCount = order.assigned_staff?.length || 0;
  const requestedCount = order.requested || 0;
  const fillPercentage = requestedCount > 0 ? Math.round((assignedCount / requestedCount) * 100) : 0;

  // Calculate ETA (hours until event)
  const eventDate = order.date ? parseISO(order.date) : new Date();
  const hoursUntil = differenceInHours(eventDate, new Date());
  const eta = hoursUntil > 24 ? `${Math.round(hoursUntil / 24)}d` : `${hoursUntil}h`;

  // Determine status
  let status = "On track";
  let statusColor = "bg-emerald-100 text-emerald-700 border-emerald-200";
  
  if (fillPercentage < 60) {
    status = "At risk";
    statusColor = "bg-red-100 text-red-700 border-red-200";
  } else if (fillPercentage < 90) {
    status = "Attention";
    statusColor = "bg-amber-100 text-amber-700 border-amber-200";
  }

  // Progress bar color based on status
  let progressColor = "bg-[#1C323E]";
  if (fillPercentage < 60) progressColor = "bg-red-500";
  else if (fillPercentage < 90) progressColor = "bg-amber-500";

  return (
    <div className="p-5 rounded-2xl bg-white border-2 border-slate-200 hover:border-[#0A39DF] transition-all shadow-sm hover:shadow-md">
      {/* Header */}
      <div className="flex items-start justify-between mb-4">
        <div>
          <h3 className="text-lg font-bold text-[#1C323E] mb-1">
            {order.business_name || "Client"} – {order.event_name}
          </h3>
        </div>
        <Badge className={`${statusColor} border font-semibold`}>
          {status}
        </Badge>
      </div>

      {/* Staff Info */}
      <div className="flex items-center gap-2 text-slate-600 mb-3">
        <Users className="w-4 h-4" />
        <span className="text-sm font-medium">
          {assignedCount} × {order.shifts?.[0]?.roles?.[0]?.role || "Staff"} 
          {requestedCount > assignedCount && (
            <span className="text-slate-400 ml-1">/ {requestedCount} needed</span>
          )}
        </span>
      </div>

      {/* Date/Time */}
      <div className="flex items-center gap-2 text-slate-600 mb-4">
        <Calendar className="w-4 h-4" />
        <span className="text-sm">
          {order.date ? format(parseISO(order.date), "EEE, HH:mm") : "Date TBD"}
          {order.shifts?.[0]?.roles?.[0]?.end_time && (
            <span>–{order.shifts[0].roles[0].end_time}</span>
          )}
        </span>
      </div>

      {/* Progress Bar */}
      <div className="mb-4">
        <div className="flex items-center justify-between text-xs text-slate-600 mb-2">
          <span className="font-semibold">{fillPercentage}%</span>
          <div className="flex items-center gap-1">
            <Clock className="w-3 h-3" />
            <span className="font-medium">ETA {eta}</span>
          </div>
        </div>
        <div className="w-full h-2 bg-slate-200 rounded-full overflow-hidden">
          <div 
            className={`h-full ${progressColor} transition-all duration-500 rounded-full`}
            style={{ width: `${fillPercentage}%` }}
          />
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-3">
        <Link to={createPageUrl(`EventDetail?id=${order.id}`)} className="flex-1">
          <Button 
            variant="outline" 
            className="w-full rounded-xl border-slate-300 hover:bg-slate-50"
          >
            View
          </Button>
        </Link>
        <Link to={createPageUrl(`EventDetail?id=${order.id}`)} className="flex-1">
          <Button className="w-full bg-[#1C323E] hover:bg-[#1C323E]/90 text-white rounded-xl font-semibold">
            Smart Assign
          </Button>
        </Link>
      </div>
    </div>
  );
}

export default function UpcomingOrdersCard({ orders }) {
  if (!orders || orders.length === 0) {
    return (
      <Card className="bg-white border-slate-200 shadow-sm">
        <CardHeader className="border-b border-slate-100 pb-4">
          <CardTitle className="text-base flex items-center gap-2">
            <MapPin className="w-5 h-5 text-[#0A39DF]" />
            Upcoming Orders
          </CardTitle>
        </CardHeader>
        <CardContent className="p-8 text-center">
          <Calendar className="w-12 h-12 mx-auto text-slate-300 mb-3" />
          <p className="text-sm text-slate-500 font-medium">No upcoming orders</p>
          <p className="text-xs text-slate-400 mt-1">New orders will appear here</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="bg-white border-slate-200 shadow-sm">
      <CardHeader className="border-b border-slate-100 pb-4">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <MapPin className="w-5 h-5 text-[#0A39DF]" />
            Upcoming Orders
          </CardTitle>
          <Badge variant="outline" className="font-semibold">
            {orders.length} {orders.length === 1 ? 'order' : 'orders'}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="p-5 space-y-4">
        {orders.map((order) => (
          <UpcomingOrderItem key={order.id} order={order} />
        ))}
      </CardContent>
    </Card>
  );
}