
import React from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Calendar, MapPin, Clock, DollarSign, CheckCircle2, AlertCircle } from "lucide-react";
import { format } from "date-fns";

// Safe date formatter
const safeFormatDate = (dateString, formatStr) => {
  if (!dateString) return "Date TBD";
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return "Date TBD";
    return format(date, formatStr);
  } catch {
    return "Date TBD";
  }
};

export default function WorkforceShifts() {
  const { data: user } = useQuery({
    queryKey: ['current-user'],
    queryFn: () => base44.auth.me(),
  });

  const { data: events } = useQuery({
    queryKey: ['workforce-events'],
    queryFn: () => base44.entities.Event.list('-date'),
    initialData: [],
  });

  // Filter events where this user is assigned
  const myShifts = events.filter(event => 
    event.assigned_staff?.some(staff => staff.staff_id === user?.id)
  );

  const upcoming = myShifts.filter(e => new Date(e.date) >= new Date()).length;
  const confirmed = myShifts.filter(e => 
    e.assigned_staff?.find(s => s.staff_id === user?.id)?.confirmed
  ).length;
  const pending = myShifts.filter(e => 
    !e.assigned_staff?.find(s => s.staff_id === user?.id)?.confirmed
  ).length;

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-[#1C323E]">My Shifts</h1>
          <p className="text-slate-500 mt-1">View and manage your upcoming shifts</p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <Card className="border-slate-200">
            <CardContent className="p-6">
              <Calendar className="w-8 h-8 text-[#0A39DF] mb-2" />
              <p className="text-sm text-slate-500">Upcoming Shifts</p>
              <p className="text-3xl font-bold text-[#1C323E]">{upcoming}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <CheckCircle2 className="w-8 h-8 text-green-600 mb-2" />
              <p className="text-sm text-slate-500">Confirmed</p>
              <p className="text-3xl font-bold text-green-600">{confirmed}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <AlertCircle className="w-8 h-8 text-yellow-600 mb-2" />
              <p className="text-sm text-slate-500">Pending Confirmation</p>
              <p className="text-3xl font-bold text-yellow-600">{pending}</p>
            </CardContent>
          </Card>
        </div>

        {/* Shifts List */}
        <div className="space-y-6">
          {myShifts.map((shift) => {
            const staffInfo = shift.assigned_staff?.find(s => s.staff_id === user?.id);
            return (
              <Card key={shift.id} className="border-slate-200">
                <CardContent className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-3">
                        <h3 className="text-xl font-bold text-[#1C323E]">{shift.event_name}</h3>
                        <Badge className={staffInfo?.confirmed ? "bg-green-100 text-green-700" : "bg-yellow-100 text-yellow-700"}>
                          {staffInfo?.confirmed ? "Confirmed" : "Pending"}
                        </Badge>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm text-slate-600">
                        <div className="flex items-center gap-2">
                          <Calendar className="w-4 h-4" />
                          {safeFormatDate(shift.date, 'PPP')}
                        </div>
                        <div className="flex items-center gap-2">
                          <MapPin className="w-4 h-4" />
                          {shift.event_location || 'Location TBD'}
                        </div>
                        <div className="flex items-center gap-2">
                          <Clock className="w-4 h-4" />
                          8:00 AM - 5:00 PM
                        </div>
                        <div className="flex items-center gap-2">
                          <DollarSign className="w-4 h-4" />
                          <span className="font-semibold">$25/hour</span>
                        </div>
                      </div>
                    </div>
                    {!staffInfo?.confirmed && (
                      <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                        Confirm Shift
                      </Button>
                    )}
                  </div>
                  {shift.notes && (
                    <div className="mt-3 p-3 bg-slate-50 rounded-lg">
                      <p className="text-sm font-semibold text-slate-700 mb-1">Event Details:</p>
                      <p className="text-sm text-slate-600">{shift.notes}</p>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      </div>
    </div>
  );
}
