'use client';

import { useEffect, useState } from 'react';
import axios from 'axios';
import { Loader2, User, Clock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { format } from 'date-fns';

export default function PendingCalloutsList() {
  const [callouts, setCallouts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState({}); // { [calloutId]: 'accepting' | 'rejecting' | null }
  const [error, setError] = useState('');

  useEffect(() => {
    fetchCallouts();
  }, []);

  const fetchCallouts = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/callouts/standalone/pending');
      setCallouts(response.data.callouts);
    } catch (err) {
      console.error('Error fetching callouts:', err);
      setError('Failed to load callouts');
    } finally {
      setLoading(false);
    }
  };

  const respondToCallout = async (calloutId, status) => {
    setActionLoading((prev) => ({ ...prev, [calloutId]: status }));
    try {
      await axios.patch(`/api/callouts/standalone/respond/${calloutId}`, { status });
      setCallouts((prev) => prev.filter((c) => c.id !== calloutId));
    } catch (err) {
      console.error(`Error updating callout:`, err);
      alert('Failed to update callout status');
    } finally {
      setActionLoading((prev) => ({ ...prev, [calloutId]: null }));
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center py-10">
        <Loader2 className="animate-spin h-6 w-6 text-gray-500" />
      </div>
    );
  }

  if (error) return <p className="text-red-500">{error}</p>;
  if (callouts.length === 0) return <p className="text-gray-500">No pending callouts at the moment.</p>;

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold text-gray-800">Pending Standalone Callouts</h2>

      {callouts.map((callout) => (
        <Card key={callout.id} className="shadow-md border border-gray-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg text-blue-600">
              <User className="w-5 h-5" />
              {callout.patient?.firstName} {callout.patient?.lastName}
            </CardTitle>
            <CardDescription className="flex items-center text-sm text-gray-500">
              <Clock className="w-4 h-4 mr-1" />
              {format(new Date(callout.createdAt), 'PPpp')}
            </CardDescription>
          </CardHeader>

          <CardContent className="space-y-2 text-gray-700">
            <p><strong>Message:</strong> {callout.message || 'No message provided'}</p>
            <p><strong>Expected Arrival:</strong> {formatTimeOption(callout.callOutTimeOption)}</p>

            <div className="flex gap-4 pt-4">
              <Button
                className="bg-green-600 hover:bg-green-700 text-white"
                disabled={actionLoading[callout.id] === 'accepting' || actionLoading[callout.id] === 'rejecting'}
                onClick={() => respondToCallout(callout.id, 'accepted')}
              >
                {actionLoading[callout.id] === 'accepting' ? (
                  <div className="flex items-center gap-1">
                    <Loader2 className="w-4 h-4 animate-spin" /> Accepting...
                  </div>
                ) : (
                  'Accept'
                )}
              </Button>

              <Button
                className="bg-red-600 hover:bg-red-700 text-white"
                disabled={actionLoading[callout.id] === 'accepting' || actionLoading[callout.id] === 'rejecting'}
                onClick={() => respondToCallout(callout.id, 'rejected')}
              >
                {actionLoading[callout.id] === 'rejecting' ? (
                  <div className="flex items-center gap-1">
                    <Loader2 className="w-4 h-4 animate-spin" /> Rejecting...
                  </div>
                ) : (
                  'Reject'
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

function formatTimeOption(option) {
  switch (option) {
    case 'within_45mins':
      return 'Within 45 minutes';
    case '1hr_45mins':
      return 'Within 1 hour 45 minutes';
    case '3_5hrs':
      return 'Within 3–5 hours';
    default:
      return 'Unknown time';
  }
}
