import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Box,
  Paper,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  Tooltip,
  Card,
  CardContent,
  Switch,
} from '@mui/material'
import {
  Add,
  Edit,
  Delete,
  Info,
  PlayArrow,
} from '@mui/icons-material'
import { strategiesApi } from '../api/strategies'
import { exchangesApi } from '../api/exchanges'
import { StrategyResponse } from '../types'
import StrategyDialog from '../components/StrategyDialog'
import SpreadChart from '../components/SpreadChart'

export default function StrategiesPage() {
  const queryClient = useQueryClient()
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingStrategy, setEditingStrategy] = useState<StrategyResponse | null>(null)
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false)
  const [strategyToDelete, setStrategyToDelete] = useState<number | null>(null)

  const { data: strategies, isLoading } = useQuery({
    queryKey: ['strategies'],
    queryFn: () => strategiesApi.listStrategies(),
  })

  const { data: exchanges } = useQuery({
    queryKey: ['exchanges'],
    queryFn: () => exchangesApi.listExchanges(),
  })

  // Query for real-time status of running strategies
  const { data: runningStatus } = useQuery({
    queryKey: ['running-strategies'],
    queryFn: () => strategiesApi.getRunningStrategies(),
    refetchInterval: 5000, // Refresh every 5 seconds
  })

  const startMutation = useMutation({
    mutationFn: (id: number) => strategiesApi.startStrategy(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['strategies'] })
    },
  })

  const stopMutation = useMutation({
    mutationFn: (id: number) => strategiesApi.stopStrategy(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['strategies'] })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: number) => strategiesApi.deleteStrategy(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['strategies'] })
      setDeleteConfirmOpen(false)
      setStrategyToDelete(null)
    },
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, updates }: { id: number; updates: any }) =>
      strategiesApi.updateStrategy(id, updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['strategies'] })
    }
  })

  const handleCreate = () => {
    setEditingStrategy(null)
    setDialogOpen(true)
  }

  const handleEdit = (strategy: StrategyResponse) => {
    setEditingStrategy(strategy)
    setDialogOpen(true)
  }

  const handleDelete = (id: number) => {
    setStrategyToDelete(id)
    setDeleteConfirmOpen(true)
  }

  const handleConfirmDelete = () => {
    if (strategyToDelete) {
      deleteMutation.mutate(strategyToDelete)
    }
  }

  const handleStart = (id: number) => {
    startMutation.mutate(id)
  }

  const handleStop = (id: number) => {
    stopMutation.mutate(id)
  }



  const getStrategyTypeLabel = (type: string) => {
    return type
      .split('_')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ')
  }

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Box>
          <Typography variant="h4">Strategy Configurations</Typography>
          <Typography variant="body2" color="text.secondary">
            Customize strategies for Autopilot or run them manually
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<Add />}
          onClick={handleCreate}
        >
          Create Strategy
        </Button>
      </Box>

      <Alert severity="info" icon={<Info />} sx={{ mb: 3 }}>
        <strong>Autopilot</strong> = Available for ML selection. <strong>Manual Run</strong> = Execute immediately (bypasses Autopilot).
      </Alert>

      {strategies && strategies.length === 0 && (
        <Card>
          <CardContent>
            <Typography variant="body1" color="text.secondary" align="center" sx={{ py: 4 }}>
              No strategies created yet. Click "Create Strategy" to get started.
            </Typography>
          </CardContent>
        </Card>
      )}

      {strategies && strategies.length > 0 && (
        <Paper>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>Name</TableCell>
                  <TableCell>Type</TableCell>
                  <TableCell>Symbol</TableCell>
                  <TableCell>Timeframe</TableCell>
                  <TableCell align="center">Autopilot</TableCell>
                  <TableCell align="center">Manual Run</TableCell>
                  <TableCell>Trading Type</TableCell>
                  <TableCell align="right">Config</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {strategies.map((strategy: StrategyResponse) => (
                  <TableRow key={strategy.id}>
                    <TableCell>
                      <Typography variant="body1" sx={{ fontWeight: 500 }}>
                        {strategy.name}
                      </Typography>
                      {strategy.description && (
                        <Typography variant="caption" color="text.secondary">
                          {strategy.description}
                        </Typography>
                      )}
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={getStrategyTypeLabel(strategy.strategy_type)}
                        size="small"
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell>
                      {strategy.parameters?.symbol || 'N/A'}
                    </TableCell>
                    <TableCell>
                      {strategy.timeframes?.join(', ') || '1h'}
                    </TableCell>
                    <TableCell align="center">
                      <Tooltip title="Toggle Autopilot Availability">
                        <Switch
                          checked={strategy.enabled}
                          onChange={(e) => {
                            const isEnabling = e.target.checked
                            // Update enabled state
                            updateMutation.mutate({
                              id: strategy.id,
                              updates: { enabled: isEnabling }
                            })
                            // Safeguard: If enabling Autopilot and it's manually running, stop it
                            if (isEnabling && strategy.running) {
                              handleStop(strategy.id)
                            }
                          }}
                          size="small"
                          color="success"
                        />
                      </Tooltip>
                    </TableCell>
                    <TableCell align="center">
                      <Tooltip title="Toggle Manual Run (Bypasses Autopilot)">
                        <Switch
                          checked={strategy.running}
                          onChange={(e) => {
                            const isStarting = e.target.checked
                            if (isStarting) {
                              handleStart(strategy.id)
                              // Safeguard: If starting manually and Autopilot is enabled, disable it
                              if (strategy.enabled) {
                                updateMutation.mutate({
                                  id: strategy.id,
                                  updates: { enabled: false }
                                })
                              }
                            } else {
                              handleStop(strategy.id)
                            }
                          }}
                          size="small"
                          color="primary"
                          disabled={startMutation.isPending || stopMutation.isPending}
                        />
                      </Tooltip>
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={strategy.paper_trading ? 'Paper' : 'Live'}
                        color={strategy.paper_trading ? 'info' : 'warning'}
                        size="small"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <Tooltip title="Edit Strategy">
                        <IconButton
                          size="small"
                          onClick={() => handleEdit(strategy)}
                        >
                          <Edit />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title="Delete Strategy">
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => handleDelete(strategy.id)}
                          disabled={deleteMutation.isPending}
                        >
                          <Delete />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      )}

      {/* Running Strategies Status */}
      {runningStatus && runningStatus.total_running > 0 && (
        <Paper sx={{ p: 2, mt: 3, bgcolor: 'success.dark', backgroundImage: 'linear-gradient(135deg, rgba(76, 175, 80, 0.1) 0%, rgba(76, 175, 80, 0.05) 100%)' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
            <PlayArrow color="success" />
            <Typography variant="h6">
              {runningStatus.total_running} Strategy Running
            </Typography>
          </Box>
          {runningStatus.strategies.map((status) => (
            <Paper key={status.strategy_id} sx={{ p: 2, mb: 1, bgcolor: 'background.paper' }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 1 }}>
                <Box>
                  <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
                    {status.name} ({status.symbol})
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Type: {status.type} | Started: {status.started_at ? new Date(status.started_at).toLocaleTimeString() : 'Unknown'}
                  </Typography>
                </Box>
                <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                  <Chip
                    label={`${status.signal_count || 0} signals`}
                    size="small"
                    color={status.signal_count && status.signal_count > 0 ? 'success' : 'default'}
                  />
                  {status.last_signal && (
                    <Chip
                      label={`Last: ${status.last_signal.type.toUpperCase()} @ $${status.last_signal.price.toFixed(2)}`}
                      size="small"
                      color={status.last_signal.type === 'buy' ? 'success' : 'error'}
                    />
                  )}
                  {status.last_tick && (
                    <Typography variant="caption" color="text.secondary">
                      Last tick: {new Date(status.last_tick).toLocaleTimeString()}
                    </Typography>
                  )}
                </Box>
              </Box>
            </Paper>
          ))}
        </Paper>
      )}

      {/* Pairs Trading Visualization */}
      {strategies && strategies.some((s: StrategyResponse) => s.strategy_type === 'pairs_trading' && (s.enabled || s.running)) && (
        <Box sx={{ mt: 3 }}>
          <Typography variant="h6" gutterBottom>
            Pairs Trading Analysis
          </Typography>
          {strategies
            .filter((s: StrategyResponse) => s.strategy_type === 'pairs_trading' && (s.enabled || s.running))
            .map((strategy: StrategyResponse) => (
              <Box key={strategy.id} sx={{ mb: 2 }}>
                <SpreadChart
                  primarySymbol={strategy.parameters?.symbol || 'BTC/USD'}
                  secondarySymbol={strategy.parameters?.second_symbol || 'ETH/USD'}
                  lookbackPeriod={strategy.parameters?.lookback_period || 20}
                  zScoreThreshold={strategy.parameters?.z_score_threshold || 2.0}
                />
              </Box>
            ))}
        </Box>
      )}

      <StrategyDialog
        open={dialogOpen}
        onClose={() => {
          setDialogOpen(false)
          setEditingStrategy(null)
        }}
        strategy={editingStrategy}
        exchanges={exchanges || []}
        onSave={() => {
          setDialogOpen(false)
          setEditingStrategy(null)
          queryClient.invalidateQueries({ queryKey: ['strategies'] })
        }}
      />

      <Dialog open={deleteConfirmOpen} onClose={() => setDeleteConfirmOpen(false)}>
        <DialogTitle>Delete Strategy</DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            Are you sure you want to delete this strategy? This action cannot be undone.
          </Alert>
          <Typography>
            This will permanently delete the strategy and all its configuration.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>Cancel</Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleConfirmDelete}
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? 'Deleting...' : 'Delete'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

