'use client';

import { use } from 'react';
import { useShift, useSignUpShift, useCancelSignUp } from '@/hooks/useShifts';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';

export default function ShiftDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params);
  const { data: shift, isLoading } = useShift(resolvedParams.id);
  const signUpMutation = useSignUpShift();
  const cancelMutation = useCancelSignUp();
  const router = useRouter();
  const { data: session } = useSession();

  if (isLoading) return <div>Loading shift...</div>;
  if (!shift) return <div>Shift not found</div>;

  const capacityPercentage = (shift.signups.length / shift.capacity) * 100;
  const isFull = shift.signups.length >= shift.capacity;
  const isPast = new Date(shift.startTime) < new Date();
  const isSignedUp = shift.signups.some((s) => s.memberId === session?.user?.id);

  const handleSignUp = async () => {
    await signUpMutation.mutateAsync(shift.id);
  };

  const handleCancelSignUp = async () => {
    await cancelMutation.mutateAsync(shift.id);
  };

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <Card>
        <CardHeader>
          <div className="flex justify-between items-start">
            <CardTitle className="text-3xl">{shift.title}</CardTitle>
            {isPast && <Badge variant="secondary">Past</Badge>}
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="grid gap-4">
            <div>
              <strong>Time:</strong> {new Date(shift.startTime).toLocaleString()} - {new Date(shift.endTime).toLocaleTimeString()}
            </div>
            {shift.location && (
              <div><strong>Location:</strong> {shift.location}</div>
            )}
            {shift.description && (
              <div><strong>Description:</strong> {shift.description}</div>
            )}
          </div>

          <div>
            <div className="flex justify-between text-sm mb-2">
              <span className="font-semibold">Capacity</span>
              <span>{shift.signups.length}/{shift.capacity} spots filled</span>
            </div>
            <Progress value={capacityPercentage} />
          </div>

          <div>
            <h3 className="font-semibold mb-2">Signed Up Members ({shift.signups.length})</h3>
            {shift.signups.length === 0 ? (
              <p className="text-sm text-muted-foreground">No sign-ups yet</p>
            ) : (
              <ul className="list-disc list-inside text-sm">
                {shift.signups.map((signup) => (
                  <li key={signup.id}>Member ID: {signup.memberId}</li>
                ))}
              </ul>
            )}
          </div>

          <div className="flex gap-2">
            {!isPast && !isFull && !isSignedUp && (
              <Button onClick={handleSignUp} disabled={signUpMutation.isPending}>
                {signUpMutation.isPending ? 'Signing up...' : 'Sign Up'}
              </Button>
            )}
            {!isPast && isSignedUp && (
              <Button variant="outline" onClick={handleCancelSignUp} disabled={cancelMutation.isPending}>
                {cancelMutation.isPending ? 'Canceling...' : 'Cancel Sign-up'}
              </Button>
            )}
            <Button variant="outline" onClick={() => router.back()}>
              Back to Shifts
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
