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

const CANDLE_INTERVAL_OPTIONS = ['1m', '5m', '15m', '1h', '4h', '1d'];

function relativeTime(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60_000);
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
}

interface CandleIntervalsCellProps {
  id: number;
  current: string[];
  isPending: boolean;
  onSave: (id: number, intervals: string[]) => void;
}

function CandleIntervalsCell({ id, current, isPending, onSave }: CandleIntervalsCellProps) {
  const [editing, setEditing] = useState(false);
  const [selected, setSelected] = useState<string[]>(current);

  function toggle(interval: string) {
    setSelected((prev) =>
      prev.includes(interval) ? prev.filter((i) => i !== interval) : [...prev, interval],
    );
  }

  function save() {
    onSave(id, selected);
    setEditing(false);
  }

  function cancel() {
    setSelected(current);
    setEditing(false);
  }

  if (editing) {
    return (
      <div style={{ minWidth: '12rem' }}>
        <div className="d-flex flex-wrap gap-1 mb-1">
          {CANDLE_INTERVAL_OPTIONS.map((interval) => (
            <Form.Check
              key={interval}
              type="checkbox"
              id={`ci-${id}-${interval}`}
              label={interval}
              checked={selected.includes(interval)}
              onChange={() => toggle(interval)}
              inline
            />
          ))}
        </div>
        <div className="d-flex gap-1">
          <Button size="sm" variant="primary" onClick={save} disabled={isPending}>
            Save
          </Button>
          <Button size="sm" variant="outline-secondary" onClick={cancel}>
            Cancel
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div
      className="d-flex flex-wrap gap-1 align-items-center"
      style={{ cursor: 'pointer' }}
      title="Click to edit candle intervals"
      onClick={() => { setSelected(current); setEditing(true); }}
    >
      {current.length > 0
        ? current.map((i) => <Badge key={i} bg="info" text="dark">{i}</Badge>)
        : <span className="text-muted fst-italic">none — click to add</span>}
    </div>
  );
}

interface CandleRetentionCellProps {
  id: number;
  current: number | null;
  isPending: boolean;
  onSet: (id: number, days: number) => void;
  onSetUnlimited: (id: number) => void;
}

function CandleRetentionCell({ id, current, isPending, onSet, onSetUnlimited }: CandleRetentionCellProps) {
  return (
    <div className="d-flex align-items-center gap-1">
      <Form.Check
        type="switch"
        id={`candle-ret-unlim-${id}`}
        checked={current === null}
        disabled={isPending}
        title={current === null ? 'Unlimited — click to set a limit' : 'Click to set unlimited'}
        onChange={() => {
          if (current === null) {
            onSet(id, 365);
          } else {
            onSetUnlimited(id);
          }
        }}
      />
      {current !== null ? (
        <Form.Control
          type="number"
          size="sm"
          min={1}
          defaultValue={current}
          style={{ width: '5.5rem' }}
          onBlur={(e) => {
            const val = parseInt(e.target.value);
            if (val > 0 && val !== current) {
              onSet(id, val);
            }
          }}
        />
      ) : (
        <span className="text-muted fst-italic">unlimited</span>
      )}
    </div>
  );
}

export default function IngestionPage() {
  const ingestConfigs = useIngestConfigs();
  const updateMutation = useUpdateIngestConfig();

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

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

      {ingestConfigs.data && (
        <Table striped bordered hover size="sm">
          <thead>
            <tr>
              <th>Exchange</th>
              <th>Pair</th>
              <th>Source</th>
              <th>Trade Ret.</th>
              <th>Candle Ret.</th>
              <th>Candle Intervals</th>
              <th>Active</th>
              <th>Last Ingested</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {ingestConfigs.data.map((cfg) => (
              <tr key={cfg.id}>
                <td>{cfg.exchange}</td>
                <td>{cfg.base_asset}-{cfg.quote_asset}</td>
                <td>{cfg.source}</td>
                <td>
                  <Form.Control
                    type="number"
                    size="sm"
                    min={1}
                    defaultValue={cfg.retention_days}
                    style={{ width: '6rem' }}
                    onBlur={(e) => {
                      const val = parseInt(e.target.value);
                      if (val > 0 && val !== cfg.retention_days) {
                        updateMutation.mutate({ id: cfg.id, retention_days: val });
                      }
                    }}
                  />
                </td>
                <td>
                  <CandleRetentionCell
                    id={cfg.id}
                    current={cfg.candle_retention_days}
                    isPending={updateMutation.isPending}
                    onSet={(id, days) => updateMutation.mutate({ id, candle_retention_days: days })}
                    onSetUnlimited={(id) => updateMutation.mutate({ id, candle_retention_unlimited: true })}
                  />
                </td>
                <td>
                  <CandleIntervalsCell
                    id={cfg.id}
                    current={cfg.candle_intervals}
                    isPending={updateMutation.isPending}
                    onSave={(id, intervals) =>
                      updateMutation.mutate({ id, candle_intervals: intervals })
                    }
                  />
                </td>
                <td>
                  <Badge bg={cfg.active ? 'success' : 'secondary'}>
                    {cfg.active ? 'Active' : 'Inactive'}
                  </Badge>
                </td>
                <td>
                  {cfg.last_ingested_date
                    ? relativeTime(cfg.last_ingested_date)
                    : <span className="text-muted">never</span>}
                </td>
                <td>{new Date(cfg.created_at).toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false })}</td>
                <td>
                  <Button
                    size="sm"
                    variant={cfg.active ? 'outline-danger' : 'outline-success'}
                    disabled={updateMutation.isPending}
                    onClick={() => updateMutation.mutate({ id: cfg.id, active: !cfg.active })}
                  >
                    {cfg.active ? 'Deactivate' : 'Activate'}
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </Table>
      )}
    </Container>
  );
}
