import { useState } from 'react';
import { Card, Button, Typography, Tag, Empty, App } from 'antd';
import { ReadOutlined, CheckOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { DashboardTraining } from './types';

interface TrainingListProps {
  trainings: DashboardTraining[];
  onRefresh: () => void;
}

export default function TrainingList({ trainings, onRefresh }: TrainingListProps) {
  const { message } = App.useApp();
  const [signingUpId, setSigningUpId] = useState<string | null>(null);

  const handleSignup = async (training: DashboardTraining) => {
    setSigningUpId(training.id);
    try {
      await api.post(`/map/shifts/volunteer/${training.id}/signup`);
      message.success('You are signed up');
      onRefresh();
    } catch {
      message.error('Failed to sign up for training');
    } finally {
      setSigningUpId(null);
    }
  };

  const upcoming = trainings.filter((t) => new Date(t.date) >= new Date());

  return (
    <Card
      styles={{
        header: { borderBottom: '1px solid rgba(255,255,255,0.06)', padding: '12px 20px', minHeight: 'auto' },
        body: { padding: 0 },
      }}
      title={
        <span style={{ fontSize: 14, fontWeight: 600 }}>
          <ReadOutlined style={{ marginRight: 8 }} />
          Volunteer Training
        </span>
      }
      extra={
        upcoming.length > 0 ? (
          <Typography.Text type="success" style={{ fontSize: 13, fontWeight: 600 }}>
            {upcoming.length} Upcoming
          </Typography.Text>
        ) : null
      }
    >
      {trainings.length === 0 ? (
        <div style={{ padding: 24 }}>
          <Empty description="No upcoming trainings" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        </div>
      ) : (
        trainings.map((training, i) => {
          const full = training.maxVolunteers > 0 && training.currentVolunteers >= training.maxVolunteers;
          return (
            <div
              key={training.id}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '12px 20px',
                borderTop: i > 0 ? '1px solid rgba(255,255,255,0.04)' : undefined,
                gap: 12,
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
                  <Tag color="volcano" style={{ margin: 0, fontSize: 11, lineHeight: '18px', padding: '0 6px' }}>
                    {training.location ? 'In Person' : 'Virtual'}
                  </Tag>
                  <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                    {dayjs(training.date).format('ddd, MMM D')} &middot; {training.startTime} - {training.endTime}
                  </Typography.Text>
                </div>
                <Typography.Text strong style={{ fontSize: 13 }}>
                  {training.title}
                </Typography.Text>
              </div>
              <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                {training.isSignedUp ? (
                  <Tag color="success" icon={<CheckOutlined />} style={{ margin: 0 }}>Signed up</Tag>
                ) : (
                  <Button
                    size="small"
                    type="primary"
                    danger
                    loading={signingUpId === training.id}
                    disabled={full}
                    onClick={() => handleSignup(training)}
                  >
                    {full ? 'Full' : 'RSVP'}
                  </Button>
                )}
              </div>
            </div>
          );
        })
      )}
    </Card>
  );
}
