import React from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Calendar, Clock, MapPin, DollarSign, CheckCircle, XCircle, AlertCircle } from "lucide-react";
import { format } from "date-fns";
import { useToast } from "@/components/ui/use-toast";
import { Textarea } from "@/components/ui/textarea";

export default function WorkerShiftProposals() {
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [declineReason, setDeclineReason] = React.useState({});

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

  const { data: proposals = [] } = useQuery({
    queryKey: ['shift-proposals', user?.id],
    queryFn: async () => {
      if (!user?.id) return [];
      const staff = await base44.entities.Staff.filter({ email: user.email });
      if (staff.length === 0) return [];
      return base44.entities.ShiftProposal.filter({ staff_id: staff[0].id });
    },
    enabled: !!user?.id,
    initialData: [],
  });

  const respondMutation = useMutation({
    mutationFn: async ({ proposalId, status, reason }) => {
      const proposal = proposals.find(p => p.id === proposalId);
      
      await base44.entities.ShiftProposal.update(proposalId, {
        proposal_status: status,
        responded_at: new Date().toISOString(),
        decline_reason: reason || null,
      });

      if (status === 'ACCEPTED') {
        // Update event with confirmed assignment
        const event = await base44.entities.Event.list();
        const targetEvent = event.find(e => e.id === proposal.event_id);
        
        if (targetEvent) {
          const updatedStaff = [
            ...(targetEvent.assigned_staff || []),
            {
              staff_id: proposal.staff_id,
              staff_name: proposal.staff_name,
              role: proposal.role,
              email: user.email,
            }
          ];

          await base44.entities.Event.update(proposal.event_id, {
            assigned_staff: updatedStaff,
            status: 'Confirmed',
          });
        }

        // Update availability
        const availability = await base44.entities.WorkerAvailability.filter({ staff_id: proposal.staff_id });
        if (availability.length > 0) {
          const current = availability[0];
          await base44.entities.WorkerAvailability.update(current.id, {
            scheduled_hours_this_period: (current.scheduled_hours_this_period || 0) + 8,
            need_work_index: Math.max(0, current.need_work_index - 10),
          });
        }
      }
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['shift-proposals'] });
      queryClient.invalidateQueries({ queryKey: ['events'] });
      
      toast({
        title: variables.status === 'ACCEPTED' ? "✅ Shift Accepted" : "Shift Declined",
        description: variables.status === 'ACCEPTED' 
          ? "The shift has been added to your schedule"
          : "The vendor will be notified of your decision",
      });
    },
  });

  const pendingProposals = proposals.filter(p => p.proposal_status === 'PENDING_WORKER_CONFIRMATION');
  const pastProposals = proposals.filter(p => p.proposal_status !== 'PENDING_WORKER_CONFIRMATION');

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-5xl mx-auto space-y-6">
        
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Shift Requests</h1>
          <p className="text-sm text-slate-500 mt-1">Review and respond to shift offers from vendors</p>
        </div>

        {/* Pending Requests */}
        <div className="space-y-4">
          <h2 className="text-lg font-bold text-slate-900">Pending Requests ({pendingProposals.length})</h2>
          
          {pendingProposals.length === 0 ? (
            <Card>
              <CardContent className="p-12 text-center">
                <AlertCircle className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                <p className="text-slate-500 font-medium">No pending shift requests</p>
                <p className="text-sm text-slate-400 mt-1">New offers will appear here</p>
              </CardContent>
            </Card>
          ) : (
            pendingProposals.map((proposal) => {
              const deadline = new Date(proposal.response_deadline);
              const isUrgent = deadline < new Date(Date.now() + 24 * 60 * 60 * 1000);
              
              return (
                <Card key={proposal.id} className={`border-2 ${isUrgent ? 'border-orange-300 bg-orange-50' : 'border-blue-300 bg-blue-50'}`}>
                  <CardHeader className="border-b">
                    <div className="flex items-start justify-between">
                      <div>
                        <CardTitle className="text-lg">{proposal.event_name}</CardTitle>
                        <p className="text-sm text-slate-600 mt-1">{proposal.role}</p>
                      </div>
                      {proposal.was_marked_unavailable && (
                        <Badge variant="outline" className="bg-yellow-100 text-yellow-800 border-yellow-300">
                          Override Unavailable
                        </Badge>
                      )}
                    </div>
                  </CardHeader>
                  <CardContent className="p-6 space-y-4">
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-slate-500" />
                        <div>
                          <p className="text-xs text-slate-500">Date</p>
                          <p className="text-sm font-semibold">{format(new Date(proposal.shift_date), 'MMM d, yyyy')}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Clock className="w-4 h-4 text-slate-500" />
                        <div>
                          <p className="text-xs text-slate-500">Time</p>
                          <p className="text-sm font-semibold">{proposal.start_time} - {proposal.end_time}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4 text-slate-500" />
                        <div>
                          <p className="text-xs text-slate-500">Location</p>
                          <p className="text-sm font-semibold">{proposal.location}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <DollarSign className="w-4 h-4 text-slate-500" />
                        <div>
                          <p className="text-xs text-slate-500">Pay</p>
                          <p className="text-sm font-semibold">${proposal.total_pay}</p>
                        </div>
                      </div>
                    </div>

                    {isUrgent && (
                      <div className="bg-orange-100 border border-orange-300 rounded-lg p-3">
                        <p className="text-sm text-orange-800 font-medium">
                          ⏰ Respond by {format(deadline, 'MMM d, h:mm a')}
                        </p>
                      </div>
                    )}

                    {declineReason[proposal.id] !== undefined && (
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-slate-700">Reason for declining (optional)</label>
                        <Textarea
                          placeholder="e.g., Schedule conflict, too far to travel, etc."
                          value={declineReason[proposal.id]}
                          onChange={(e) => setDeclineReason({ ...declineReason, [proposal.id]: e.target.value })}
                          rows={2}
                        />
                      </div>
                    )}

                    <div className="flex gap-3">
                      {declineReason[proposal.id] === undefined ? (
                        <>
                          <Button
                            onClick={() => respondMutation.mutate({ proposalId: proposal.id, status: 'ACCEPTED' })}
                            className="flex-1 bg-green-600 hover:bg-green-700"
                            disabled={respondMutation.isPending}
                          >
                            <CheckCircle className="w-4 h-4 mr-2" />
                            Accept Shift
                          </Button>
                          <Button
                            onClick={() => setDeclineReason({ ...declineReason, [proposal.id]: '' })}
                            variant="outline"
                            className="flex-1 border-red-300 text-red-700 hover:bg-red-50"
                          >
                            <XCircle className="w-4 h-4 mr-2" />
                            Decline
                          </Button>
                        </>
                      ) : (
                        <>
                          <Button
                            onClick={() => respondMutation.mutate({ 
                              proposalId: proposal.id, 
                              status: 'DECLINED',
                              reason: declineReason[proposal.id]
                            })}
                            className="flex-1 bg-red-600 hover:bg-red-700"
                            disabled={respondMutation.isPending}
                          >
                            Confirm Decline
                          </Button>
                          <Button
                            onClick={() => {
                              const newReasons = { ...declineReason };
                              delete newReasons[proposal.id];
                              setDeclineReason(newReasons);
                            }}
                            variant="outline"
                          >
                            Cancel
                          </Button>
                        </>
                      )}
                    </div>
                  </CardContent>
                </Card>
              );
            })
          )}
        </div>

        {/* Past Responses */}
        {pastProposals.length > 0 && (
          <div className="space-y-4">
            <h2 className="text-lg font-bold text-slate-900">Past Responses</h2>
            {pastProposals.map((proposal) => (
              <Card key={proposal.id} className="border">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-semibold text-slate-900">{proposal.event_name}</p>
                      <p className="text-sm text-slate-500">{format(new Date(proposal.shift_date), 'MMM d, yyyy')}</p>
                    </div>
                    <Badge className={
                      proposal.proposal_status === 'ACCEPTED' 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-red-100 text-red-800'
                    }>
                      {proposal.proposal_status}
                    </Badge>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}