import {
  Alert,
  Badge,
  Button,
  Container,
  Spinner,
  Table,
} from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { useSubscriptions, useDeactivateSubscription } from '../api/hooks';
import AppBreadcrumb from '../components/AppBreadcrumb';

export default function SubscriptionsPage() {
  const subscriptions = useSubscriptions(false);
  const deactivateMutation = useDeactivateSubscription();

  return (
    <Container>
      <AppBreadcrumb />
      <div className="d-flex justify-content-between align-items-center mb-3">
        <h5 className="mb-0">Subscriptions</h5>
        <Link to="/subscriptions/new" className="btn btn-primary btn-sm">
          Add Subscription
        </Link>
      </div>

      {subscriptions.isLoading && <Spinner animation="border" />}
      {subscriptions.isError && (
        <Alert variant="danger">{(subscriptions.error as Error).message}</Alert>
      )}

      {subscriptions.data && (
        <Table striped bordered hover size="sm">
          <thead>
            <tr>
              <th>ID</th>
              <th>Exchange</th>
              <th>Pair</th>
              <th>Type</th>
              <th>Active</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {subscriptions.data.map((sub) => (
              <tr key={sub.id}>
                <td>{sub.id}</td>
                <td>{sub.exchange}</td>
                <td>{sub.base_asset}-{sub.quote_asset}</td>
                <td>{sub.sub_kind}</td>
                <td>
                  <Badge bg={sub.active ? 'success' : 'secondary'}>
                    {sub.active ? 'Active' : 'Inactive'}
                  </Badge>
                </td>
                <td>{new Date(sub.created_at).toLocaleString()}</td>
                <td>
                  {sub.active && (
                    <Button
                      size="sm"
                      variant="outline-danger"
                      disabled={deactivateMutation.isPending}
                      onClick={() => deactivateMutation.mutate(sub.id)}
                    >
                      Deactivate
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </Table>
      )}
    </Container>
  );
}
