import React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Calendar, MapPin, Users, DollarSign, Clock, Building2, FileText, X, Star, ExternalLink, Edit3, User } from "lucide-react";
import { format, parseISO, isValid } from "date-fns";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";

const safeParseDate = (dateString) => {
  if (!dateString) return null;
  try {
    const date = typeof dateString === 'string' ? parseISO(dateString) : new Date(dateString);
    return isValid(date) ? date : null;
  } catch { return null; }
};

const safeFormatDate = (dateString, formatString) => {
  const date = safeParseDate(dateString);
  return date ? format(date, formatString) : '—';
};

const convertTo12Hour = (time24) => {
  if (!time24) return "-";
  try {
    const [hours, minutes] = time24.split(':');
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? 'PM' : 'AM';
    const hour12 = hour % 12 || 12;
    return `${hour12}:${minutes} ${ampm}`;
  } catch {
    return time24;
  }
};

const getStatusBadge = (status) => {
  const statusConfig = {
    'Draft': { bg: 'bg-slate-500', text: 'Draft' },
    'Pending': { bg: 'bg-amber-500', text: 'Pending' },
    'Partial Staffed': { bg: 'bg-orange-500', text: 'Partial Staffed' },
    'Fully Staffed': { bg: 'bg-emerald-500', text: 'Fully Staffed' },
    'Active': { bg: 'bg-blue-500', text: 'Active' },
    'Completed': { bg: 'bg-slate-400', text: 'Completed' },
    'Canceled': { bg: 'bg-red-500', text: 'Canceled' },
  };
  
  const config = statusConfig[status] || { bg: 'bg-slate-400', text: status };
  
  return (
    <Badge className={`${config.bg} text-white px-4 py-1.5 font-semibold`}>
      {config.text}
    </Badge>
  );
};

export default function OrderDetailModal({ open, onClose, order, onCancel }) {
  const navigate = useNavigate();
  
  const { data: allStaff = [] } = useQuery({
    queryKey: ['staff-for-order-modal'],
    queryFn: () => base44.entities.Staff.list(),
    enabled: open,
  });

  if (!order) return null;

  const canEditOrder = (order) => {
    const eventDate = safeParseDate(order.date);
    const now = new Date();
    return order.status !== "Completed" && 
           order.status !== "Canceled" && 
           eventDate && eventDate > now;
  };

  const canCancelOrder = (order) => {
    return order.status !== "Completed" && order.status !== "Canceled";
  };

  const handleViewFullOrder = () => {
    navigate(createPageUrl(`EventDetail?id=${order.id}`));
  };

  const handleEditOrder = () => {
    navigate(createPageUrl(`EditEvent?id=${order.id}`));
  };

  const handleCancelOrder = () => {
    onClose();
    if (onCancel) {
      onCancel(order);
    }
  };

  const assignedCount = order.assigned_staff?.length || 0;
  const requestedCount = order.requested || 0;
  const assignmentProgress = requestedCount > 0 ? Math.round((assignedCount / requestedCount) * 100) : 0;

  // Get event times
  const firstShift = order.shifts?.[0];
  const rolesInFirstShift = firstShift?.roles || [];
  const startTime = rolesInFirstShift.length > 0 ? convertTo12Hour(rolesInFirstShift[0].start_time) : "-";
  const endTime = rolesInFirstShift.length > 0 ? convertTo12Hour(rolesInFirstShift[0].end_time) : "-";

  // Get staff details
  const getStaffDetails = (staffId) => {
    return allStaff.find(s => s.id === staffId) || {};
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader className="border-b pb-4">
          <div className="flex items-start justify-between">
            <div>
              <DialogTitle className="text-2xl font-bold text-slate-900">{order.event_name}</DialogTitle>
              <p className="text-sm text-slate-500 mt-1">Order Details & Information</p>
            </div>
            {getStatusBadge(order.status)}
          </div>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Order Information */}
          <div className="bg-slate-50 rounded-lg p-4">
            <h3 className="font-semibold text-slate-900 mb-4">Order Information</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center">
                  <Calendar className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-xs text-slate-500">Event Date</p>
                  <p className="font-bold text-slate-900 text-sm">{safeFormatDate(order.date, 'MMM dd, yyyy')}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-purple-50 rounded-lg flex items-center justify-center">
                  <MapPin className="w-5 h-5 text-purple-600" />
                </div>
                <div>
                  <p className="text-xs text-slate-500">Location</p>
                  <p className="font-bold text-slate-900 text-sm">{order.hub || order.event_location || "—"}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-50 rounded-lg flex items-center justify-center">
                  <Users className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <p className="text-xs text-slate-500">Staff Assigned</p>
                  <p className="font-bold text-slate-900 text-sm">{assignedCount} / {requestedCount}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-amber-50 rounded-lg flex items-center justify-center">
                  <DollarSign className="w-5 h-5 text-amber-600" />
                </div>
                <div>
                  <p className="text-xs text-slate-500">Total Cost</p>
                  <p className="font-bold text-slate-900 text-sm">${(order.total || 0).toLocaleString()}</p>
                </div>
              </div>
            </div>
          </div>

          {/* Business & Time Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-slate-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-2">
                <Building2 className="w-4 h-4 text-blue-600" />
                <p className="text-xs text-slate-500 font-semibold">Business</p>
              </div>
              <p className="font-bold text-slate-900">{order.business_name || "—"}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-2">
                <Clock className="w-4 h-4 text-purple-600" />
                <p className="text-xs text-slate-500 font-semibold">Time</p>
              </div>
              <p className="font-bold text-slate-900">{startTime} - {endTime}</p>
            </div>
          </div>

          {/* Event Location & POC */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-slate-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-2">
                <MapPin className="w-4 h-4 text-emerald-600" />
                <p className="text-xs text-slate-500 font-semibold">Event Location</p>
              </div>
              <p className="font-bold text-slate-900">{order.event_location || order.hub || "—"}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-2">
                <User className="w-4 h-4 text-indigo-600" />
                <p className="text-xs text-slate-500 font-semibold">Point of Contact</p>
              </div>
              <div>
                <p className="font-bold text-slate-900">{order.client_name || order.manager_name || "—"}</p>
                {order.client_phone && (
                  <p className="text-xs text-slate-500 mt-1">{order.client_phone}</p>
                )}
                {order.client_email && (
                  <p className="text-xs text-slate-500">{order.client_email}</p>
                )}
              </div>
            </div>
          </div>

          {/* Shifts & Roles */}
          {order.shifts && order.shifts.length > 0 && (
            <div>
              <h3 className="font-semibold text-slate-900 mb-3">Shifts & Staff Requirements</h3>
              <div className="space-y-3">
                {order.shifts.map((shift, idx) => (
                  <div key={idx} className="bg-slate-50 rounded-lg p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div>
                        <p className="font-semibold text-slate-900">{shift.shift_name || `Shift ${idx + 1}`}</p>
                        {shift.location && (
                          <p className="text-xs text-slate-500 flex items-center gap-1 mt-1">
                            <MapPin className="w-3 h-3" />
                            {shift.location}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="space-y-2">
                      {shift.roles?.map((role, roleIdx) => (
                        <div key={roleIdx} className="flex items-center justify-between bg-white rounded p-3">
                          <div>
                            <p className="font-medium text-slate-900">{role.role}</p>
                            <p className="text-xs text-slate-500">{role.department || "—"}</p>
                          </div>
                          <div className="flex items-center gap-4">
                            <div className="text-right">
                              <p className="text-xs text-slate-500">Required</p>
                              <p className="font-bold text-slate-900">{role.count || 0}</p>
                            </div>
                            <div className="text-right">
                              <p className="text-xs text-slate-500">Time</p>
                              <p className="font-medium text-slate-900 text-sm">
                                {convertTo12Hour(role.start_time)} - {convertTo12Hour(role.end_time)}
                              </p>
                            </div>
                            <div className="text-right">
                              <p className="text-xs text-slate-500">Rate</p>
                              <p className="font-bold text-emerald-600">${role.cost_per_hour}/hr</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Assigned Staff */}
          {order.assigned_staff && order.assigned_staff.length > 0 && (
            <div>
              <h3 className="font-semibold text-slate-900 mb-3">Assigned Staff ({order.assigned_staff.length})</h3>
              <div className="bg-slate-50 rounded-lg p-4">
                <div className="space-y-3">
                  {order.assigned_staff.map((staff, idx) => {
                    const staffDetails = getStaffDetails(staff.staff_id);
                    const rating = staffDetails.rating || 0;
                    const reliability = staffDetails.reliability_score || 0;
                    const totalShifts = staffDetails.total_shifts || 0;
                    
                    return (
                      <div key={idx} className="flex items-center justify-between bg-white rounded-lg p-4">
                        <div className="flex items-center gap-3">
                          <Avatar className="w-12 h-12">
                            <AvatarImage 
                              src={staffDetails.profile_picture || staffDetails.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(staff.staff_name || 'Staff')}&background=10b981&color=fff&size=128`} 
                              alt={staff.staff_name} 
                            />
                          </Avatar>
                          <div>
                            <p className="font-semibold text-slate-900">{staff.staff_name}</p>
                            <p className="text-sm text-slate-500">{staffDetails.position || staff.role || "—"}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-6">
                          <div className="text-center">
                            <div className="flex items-center gap-1 mb-1">
                              <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
                              <span className="font-bold text-slate-900">{rating.toFixed(1)}</span>
                            </div>
                            <p className="text-xs text-slate-500">Rating</p>
                          </div>
                          <div className="text-center">
                            <p className="font-bold text-emerald-600">{reliability}%</p>
                            <p className="text-xs text-slate-500">On-Time Arrival</p>
                          </div>
                          <div className="text-center">
                            <p className="font-bold text-blue-600">{totalShifts}</p>
                            <p className="text-xs text-slate-500">Jobs</p>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {/* Notes */}
          {order.notes && (
            <div>
              <h3 className="font-semibold text-slate-900 mb-2">Additional Notes</h3>
              <div className="bg-slate-50 rounded-lg p-4">
                <p className="text-slate-700 text-sm whitespace-pre-wrap">{order.notes}</p>
              </div>
            </div>
          )}
          </div>

          <DialogFooter className="border-t pt-4">
          <div className="flex items-center justify-between w-full gap-3">
            <Button
              variant="outline"
              onClick={handleViewFullOrder}
              className="flex items-center gap-2"
            >
              <ExternalLink className="w-4 h-4" />
              View Full Order
            </Button>
            <div className="flex items-center gap-2">
              {canEditOrder(order) && (
                <Button
                  variant="outline"
                  onClick={handleEditOrder}
                  className="flex items-center gap-2"
                >
                  <Edit3 className="w-4 h-4" />
                  Edit Order
                </Button>
              )}
              {canCancelOrder(order) && (
                <Button
                  variant="destructive"
                  onClick={handleCancelOrder}
                  className="flex items-center gap-2"
                >
                  <X className="w-4 h-4" />
                  Cancel Order
                </Button>
              )}
            </div>
          </div>
          </DialogFooter>
          </DialogContent>
          </Dialog>
          );
          }