import { Alert, Button, Card, Col, Container, Form, Row, Spinner, Tab, Tabs } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import AppBreadcrumb from '../components/AppBreadcrumb';
import { useCreateStrategy } from '../api/hooks';
import { convertPineScript } from '../lib/pinescript';

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

const EXAMPLE_RULES = JSON.stringify(
  [
    {
      comment: 'Enter long: liquidity sweep below 20-bar low, closes above prior high',
      when: {
        kind: 'all_of',
        conditions: [
          { kind: 'position', state: 'flat' },
          {
            kind: 'compare',
            left: { kind: 'field', field: 'low' },
            op: '<',
            right: { kind: 'func', name: 'lowest', field: 'low', period: 20, offset: 1 },
          },
          {
            kind: 'compare',
            left: { kind: 'field', field: 'close' },
            op: '>',
            right: { kind: 'field', field: 'high', offset: 1 },
          },
        ],
      },
      then: { side: 'buy', quantity: '0.001' },
    },
    {
      comment: 'Exit long: opposite sweep fires while long',
      when: {
        kind: 'all_of',
        conditions: [
          { kind: 'position', state: 'long' },
          {
            kind: 'compare',
            left: { kind: 'field', field: 'high' },
            op: '>',
            right: { kind: 'func', name: 'highest', field: 'high', period: 20, offset: 1 },
          },
          {
            kind: 'compare',
            left: { kind: 'field', field: 'close' },
            op: '<',
            right: { kind: 'field', field: 'low', offset: 1 },
          },
        ],
      },
      then: { side: 'sell', quantity: '0.001' },
    },
  ],
  null,
  2,
);

const EXAMPLE_PINESCRIPT = `// Example: EMA Crossover
//@version=5
strategy("EMA Crossover", overlay=true, default_qty_value=0.001)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)

longCond = ta.crossover(fast, slow)
shortCond = ta.crossunder(fast, slow)

if longCond
    strategy.entry("Long", strategy.long)

if shortCond
    strategy.close("Long")
    strategy.entry("Short", strategy.short)

if ta.crossover(slow, fast)
    strategy.close("Short")
`;

function tryParseJson(s: string): unknown | null {
  try {
    return JSON.parse(s);
  } catch {
    return null;
  }
}

export default function AddStrategyPage() {
  const navigate = useNavigate();
  const createMutation = useCreateStrategy();

  const [name, setName] = useState<string>('');
  const [description, setDescription] = useState<string>('');
  const [interval, setInterval] = useState<string>('1h');
  const [rulesJson, setRulesJson] = useState<string>(EXAMPLE_RULES);

  // PineScript tab state
  const [pineSource, setPineSource] = useState<string>(EXAMPLE_PINESCRIPT);
  const [convertWarnings, setConvertWarnings] = useState<Array<{ line: number; message: string }>>(
    [],
  );

  const parsedRules = tryParseJson(rulesJson);
  const rulesValid = Array.isArray(parsedRules);

  function handleConvert() {
    const result = convertPineScript(pineSource);
    setConvertWarnings(result.warnings);
    if (result.rules.length > 0) {
      setRulesJson(JSON.stringify(result.rules, null, 2));
      if (result.interval) {
        setInterval(result.interval);
      }
    }
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!rulesValid) return;

    const config = {
      type: 'rule_based',
      candle_interval: interval,
      rules: parsedRules,
    };

    createMutation.mutate(
      {
        config,
        ...(name.trim() ? { name: name.trim() } : {}),
        ...(description.trim() ? { description: description.trim() } : {}),
      },
      {
        onSuccess: (strategy) => {
          navigate(`/strategies/${strategy.id}`);
        },
      },
    );
  }

  return (
    <Container>
      <AppBreadcrumb />
      <Row>
        <Col lg={8} xl={7}>
          <Card>
            <Card.Header>New Rule-Based Strategy</Card.Header>
            <Card.Body>
              <Form onSubmit={handleSubmit}>
                {/* Name (optional) */}
                <Form.Group className="mb-3">
                  <Form.Label>
                    Name{' '}
                    <span className="text-muted fw-normal" style={{ fontSize: '0.85em' }}>
                      (optional)
                    </span>
                  </Form.Label>
                  <Form.Control
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="e.g. ema crossover"
                  />
                  <Form.Text className="text-muted">
                    Named strategies can be versioned and tracked over time.
                  </Form.Text>
                </Form.Group>

                {/* Description (optional) */}
                <Form.Group className="mb-3">
                  <Form.Label>
                    Description{' '}
                    <span className="text-muted fw-normal" style={{ fontSize: '0.85em' }}>
                      (optional, markdown)
                    </span>
                  </Form.Label>
                  <Form.Control
                    as="textarea"
                    rows={3}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Describe the strategy's intent, signals, and limitations..."
                    spellCheck
                  />
                </Form.Group>

                {/* Candle interval */}
                <Form.Group className="mb-3">
                  <Form.Label>Candle Interval</Form.Label>
                  <Form.Select
                    value={interval}
                    onChange={(e) => setInterval(e.target.value)}
                  >
                    {CANDLE_INTERVALS.map((iv) => (
                      <option key={iv} value={iv}>
                        {iv}
                      </option>
                    ))}
                  </Form.Select>
                  <Form.Text className="text-muted">
                    Signals are evaluated once per closed candle.
                  </Form.Text>
                </Form.Group>

                {/* Rules input with PineScript / JSON tabs */}
                <Form.Group className="mb-3">
                  <Form.Label className="mb-2">Rules</Form.Label>
                  <Tabs defaultActiveKey="json" className="mb-2" id="rules-tabs">
                    <Tab eventKey="json" title="JSON">
                      <Form.Control
                        as="textarea"
                        rows={22}
                        value={rulesJson}
                        onChange={(e) => setRulesJson(e.target.value)}
                        isInvalid={rulesJson.trim() !== '' && !rulesValid}
                        isValid={rulesValid}
                        spellCheck={false}
                        style={{ fontFamily: 'monospace', fontSize: '0.8em' }}
                      />
                      {rulesJson.trim() !== '' && !rulesValid && (
                        <Form.Control.Feedback type="invalid">
                          Invalid JSON — must be an array of rule objects.
                        </Form.Control.Feedback>
                      )}
                      <Form.Text className="text-muted">
                        Each rule has a <code>when</code> condition and a <code>then</code> action.
                      </Form.Text>
                    </Tab>
                    <Tab eventKey="pinescript" title="PineScript">
                      <Form.Control
                        as="textarea"
                        rows={18}
                        value={pineSource}
                        onChange={(e) => setPineSource(e.target.value)}
                        spellCheck={false}
                        style={{ fontFamily: 'monospace', fontSize: '0.8em' }}
                        placeholder="Paste PineScript strategy here..."
                      />
                      <div className="mt-2 d-flex align-items-center gap-2">
                        <Button
                          variant="outline-secondary"
                          size="sm"
                          onClick={handleConvert}
                          disabled={!pineSource.trim()}
                        >
                          Convert → JSON
                        </Button>
                        <span className="text-muted" style={{ fontSize: '0.8em' }}>
                          Converts supported constructs and populates the JSON tab.
                        </span>
                      </div>
                      {convertWarnings.length > 0 && (
                        <div className="mt-2">
                          {convertWarnings.map((w, i) => (
                            <Alert
                              key={i}
                              variant="warning"
                              className="py-1 px-2 mb-1"
                              style={{ fontSize: '0.8em' }}
                            >
                              <strong>Line {w.line}:</strong> {w.message}
                            </Alert>
                          ))}
                        </div>
                      )}
                      <Form.Text className="text-muted">
                        Supports OHLCV fields, ta.ema/sma/rsi/highest/lowest/stdev,
                        ta.crossover/crossunder, comparisons, and boolean logic.
                        Unsupported constructs are warned and skipped.
                      </Form.Text>
                    </Tab>
                  </Tabs>
                </Form.Group>

                <div className="d-flex gap-2">
                  <Button
                    type="submit"
                    disabled={createMutation.isPending || !rulesValid}
                  >
                    {createMutation.isPending ? (
                      <Spinner size="sm" animation="border" />
                    ) : (
                      'Save Strategy'
                    )}
                  </Button>
                  <Button
                    variant="outline-secondary"
                    onClick={() => navigate('/strategies')}
                  >
                    Cancel
                  </Button>
                </div>

                {createMutation.isError && (
                  <Alert variant="danger" className="mt-3">
                    {createMutation.error instanceof Error
                      ? createMutation.error.message
                      : String(createMutation.error)}
                  </Alert>
                )}
              </Form>
            </Card.Body>
          </Card>
        </Col>

        {/* Quick reference */}
        <Col lg={4} xl={5}>
          <Card className="mb-3">
            <Card.Header>DSL Reference</Card.Header>
            <Card.Body style={{ fontSize: '0.8em' }}>
              <p className="mb-1 fw-semibold">Conditions</p>
              <pre className="mb-2">{`{ "kind": "position", "state": "flat"|"long"|"short" }
{ "kind": "compare", "left": <expr>,
  "op": ">"|"<"|">="|"<="|"==", "right": <expr> }
{ "kind": "cross_over"|"cross_under",
  "left": <expr>, "right": <expr> }
{ "kind": "event_count", "condition": <cond>,
  "period": 20, "op": ">=", "count": 1 }
{ "kind": "all_of"|"any_of", "conditions": [...] }
{ "kind": "not", "condition": <cond> }`}</pre>

              <p className="mb-1 fw-semibold">Expressions</p>
              <pre className="mb-2">{`{ "kind": "literal", "value": "100.5" }
{ "kind": "field",
  "field": "open"|"high"|"low"|"close"|"volume",
  "offset": 0, "timeframe": "1h" }
{ "kind": "func",
  "name": "sma"|"ema"|"wma"|"rsi"
        |"highest"|"lowest"|"std_dev"|"sum"
        |"atr"|"adx"|"supertrend",
  "field": "close", "period": 20,
  "multiplier": "3.0",  // supertrend only
  "offset": 0, "timeframe": "1d" }
{ "kind": "apply_func", "name": "ema",
  "input": <expr>, "period": 20, "offset": 0 }
{ "kind": "bin_op", "op": "add"|"sub"|"mul"|"div",
  "left": <expr>, "right": <expr> }
{ "kind": "unary_op", "op": "abs"|"neg"|"sqrt"|"log",
  "operand": <expr> }
{ "kind": "bars_since", "condition": <cond>, "period": 20 }`}</pre>

              <p className="mb-1 fw-semibold">Multi-timeframe</p>
              <pre className="mb-0">{`// field and func accept an optional "timeframe" to
// read from a different candle interval. Evaluation
// is gated on the primary (candle_interval) close.
{ "kind": "func", "name": "sma", "field": "close",
  "period": 200, "timeframe": "1d" }
// Each extra timeframe needs candle data backfilled.`}</pre>
            </Card.Body>
          </Card>

          <Card>
            <Card.Header>PineScript Coverage</Card.Header>
            <Card.Body style={{ fontSize: '0.8em' }}>
              <p className="mb-1 fw-semibold text-success">Supported</p>
              <ul className="mb-2 ps-3">
                <li>OHLCV fields + bar offsets (<code>close[1]</code>)</li>
                <li>ta.ema, ta.sma, ta.rsi, ta.stdev</li>
                <li>ta.highest, ta.lowest</li>
                <li>ta.crossover, ta.crossunder</li>
                <li>Arithmetic (+, -, *, /)</li>
                <li>Comparisons, and/or/not</li>
                <li>strategy.entry / strategy.close</li>
                <li>if block conditions</li>
              </ul>
              <p className="mb-1 fw-semibold text-danger">Not supported</p>
              <ul className="mb-0 ps-3">
                <li>Nested functions (EMA of RSI)</li>
                <li>ta.atr, ta.macd, ta.stoch</li>
                <li>Stop/limit orders</li>
                <li>
                  Multi-timeframe (<code>request.security</code>)
                  <br />
                  <span className="text-muted" style={{ fontSize: '0.9em' }}>
                    Use <code>"timeframe"</code> field in DSL directly
                  </span>
                </li>
                <li>Dynamic position sizing</li>
              </ul>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}
