import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  Box,
  Grid,
  Paper,
  Typography,
  Card,
  CardContent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Tab,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  Alert,
} from '@mui/material'
import { Download, Description } from '@mui/icons-material'
import { portfolioApi } from '../api/portfolio'
import { reportingApi } from '../api/reporting'
import { useSnackbar } from '../contexts/SnackbarContext'
import LoadingSkeleton from '../components/LoadingSkeleton'
import DataFreshness from '../components/DataFreshness'
import PositionCard from '../components/PositionCard'
import HelpTooltip from '../components/HelpTooltip'
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
} from 'recharts'

interface TabPanelProps {
  children?: React.ReactNode
  index: number
  value: number
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props
  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
    </div>
  )
}

export default function PortfolioPage() {
  const [tabValue, setTabValue] = useState(0)
  const { showError, showSuccess } = useSnackbar()

  const { data: portfolio, isLoading } = useQuery({
    queryKey: ['portfolio'],
    queryFn: () => portfolioApi.getCurrentPortfolio(),
    refetchInterval: 5000,
  })

  const { data: history } = useQuery({
    queryKey: ['portfolio-history'],
    queryFn: () => portfolioApi.getPortfolioHistory(30),
  })

  const { data: riskMetrics } = useQuery({
    queryKey: ['portfolio-risk-metrics'],
    queryFn: () => portfolioApi.getRiskMetrics(30),
    refetchInterval: 30000,
  })

  const chartData = history
    ? history.dates.map((date, i) => ({
      date: new Date(date).toLocaleDateString(),
      value: history.values[i],
      pnl: history.pnl[i],
    }))
    : []

  if (isLoading) {
    return <LoadingSkeleton variant="card" rows={3} />
  }

  // Calculate allocation data for pie chart
  const allocationData = portfolio?.positions.map((pos) => ({
    name: pos.symbol,
    value: (pos.quantity ?? 0) * (pos.current_price ?? 0),
  })) || []

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8', '#82ca9d']

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h4">Portfolio</Typography>
        {portfolio && <DataFreshness timestamp={portfolio.timestamp} />}
      </Box>

      <Paper sx={{ mb: 3 }}>
        <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)}>
          <Tab label="Overview" />
          <Tab label="Allocations" />
          <Tab label="Reports & Export" />
        </Tabs>
      </Paper>

      <TabPanel value={tabValue} index={0}>
        <Grid container spacing={3}>
          {/* Summary Cards */}
          {portfolio && (
            <>
              <Grid item xs={12} md={3}>
                <Card>
                  <CardContent>
                    <Typography color="textSecondary" gutterBottom>
                      Current Value
                    </Typography>
                    <Typography variant="h4">
                      ${(portfolio.performance?.current_value ?? 0).toFixed(2)}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} md={3}>
                <Card>
                  <CardContent>
                    <Typography color="textSecondary" gutterBottom>
                      Unrealized P&L
                    </Typography>
                    <Typography
                      variant="h4"
                      sx={{
                        color: (portfolio.performance?.unrealized_pnl ?? 0) >= 0 ? 'success.main' : 'error.main',
                      }}
                    >
                      ${(portfolio.performance?.unrealized_pnl ?? 0).toFixed(2)}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid item xs={12} md={3}>
                <Card>
                  <CardContent>
                    <Typography color="textSecondary" gutterBottom>
                      Realized P&L
                    </Typography>
                    <Typography
                      variant="h4"
                      sx={{
                        color: (portfolio.performance?.realized_pnl ?? 0) >= 0 ? 'success.main' : 'error.main',
                      }}
                    >
                      ${(portfolio.performance?.realized_pnl ?? 0).toFixed(2)}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              {history && history.values.length >= 2 && (
                <Grid item xs={12} md={3}>
                  <Card>
                    <CardContent>
                      <Typography color="textSecondary" gutterBottom>
                        Daily Change
                      </Typography>
                      <Typography
                        variant="h4"
                        sx={{
                          color:
                            (history.values[history.values.length - 1] - history.values[history.values.length - 2]) >= 0
                              ? 'success.main'
                              : 'error.main',
                        }}
                      >
                        {(() => {
                          const change = history.values[history.values.length - 1] - history.values[history.values.length - 2]
                          const changePercent = history.values[history.values.length - 2] > 0
                            ? (change / history.values[history.values.length - 2]) * 100
                            : 0
                          return `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`
                        })()}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              )}
            </>
          )}

          {/* Portfolio Chart */}
          <Grid item xs={12}>
            <Paper sx={{ p: 3 }}>
              <Typography variant="h6" gutterBottom>
                Portfolio Value History
              </Typography>
              <ResponsiveContainer width="100%" height={350}>
                <LineChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="value" stroke="#2196F3" name="Portfolio Value" />
                  <Line type="monotone" dataKey="pnl" stroke="#00E676" name="P&L" />
                </LineChart>
              </ResponsiveContainer>
            </Paper>
          </Grid>

          {/* Risk Metrics */}
          {riskMetrics && (
            <Grid item xs={12}>
              <Paper sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  Risk Metrics (30 days)
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={6} sm={4} md={2}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography color="textSecondary" variant="body2">Sharpe Ratio</Typography>
                        <Typography variant="h6">{(riskMetrics.sharpe_ratio ?? 0).toFixed(2)}</Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography color="textSecondary" variant="body2">Sortino Ratio</Typography>
                        <Typography variant="h6">{(riskMetrics.sortino_ratio ?? 0).toFixed(2)}</Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography color="textSecondary" variant="body2">Max Drawdown</Typography>
                        <Typography variant="h6" sx={{ color: (riskMetrics.max_drawdown ?? 0) < 0 ? 'error.main' : 'text.primary' }}>
                          {((riskMetrics.max_drawdown ?? 0) * 100).toFixed(2)}%
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography color="textSecondary" variant="body2">Win Rate</Typography>
                        <Typography variant="h6">{((riskMetrics.win_rate ?? 0) * 100).toFixed(1)}%</Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={6} sm={4} md={2}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography color="textSecondary" variant="body2">Total Return</Typography>
                        <Typography variant="h6" sx={{ color: (riskMetrics.total_return ?? 0) >= 0 ? 'success.main' : 'error.main' }}>
                          {(riskMetrics.total_return_percent ?? 0).toFixed(2)}%
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                </Grid>
              </Paper>
            </Grid>
          )}

          {/* Holdings - Card View */}
          <Grid item xs={12}>
            <Paper sx={{ p: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6">
                  Holdings
                </Typography>
                <HelpTooltip title="Click 'Close Position' on any position card to close it" />
              </Box>
              {portfolio && portfolio.positions.length > 0 ? (
                <Grid container spacing={2}>
                  {portfolio.positions.map((pos) => (
                    <Grid item xs={12} md={6} lg={4} key={pos.symbol}>
                      <PositionCard
                        position={pos}
                        paperTrading={true}
                        onClose={() => {
                          // Position will be closed via PositionCard
                        }}
                      />
                    </Grid>
                  ))}
                </Grid>
              ) : (
                <Typography variant="body1" color="text.secondary" align="center" sx={{ py: 4 }}>
                  No holdings
                </Typography>
              )}
            </Paper>
          </Grid>
        </Grid>
      </TabPanel>

      <TabPanel value={tabValue} index={1}>
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            Portfolio Allocation
            <HelpTooltip title="Visual representation of your portfolio distribution by asset" />
          </Typography>
          {allocationData.length > 0 ? (
            <ResponsiveContainer width="100%" height={400}>
              <PieChart>
                <Pie
                  data={allocationData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={120}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {allocationData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip formatter={(value: number) => `$${value.toFixed(2)}`} />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          ) : (
            <Typography variant="body1" color="text.secondary" align="center" sx={{ py: 4 }}>
              No allocation data available
            </Typography>
          )}
        </Paper>
      </TabPanel>

      <TabPanel value={tabValue} index={2}>
        <ReportsSection showError={showError} showSuccess={showSuccess} />
      </TabPanel>
    </Box>
  )
}

// Reports Section (merged from ReportingPage)
function ReportsSection({ showError, showSuccess }: { showError: (msg: string) => void; showSuccess: (msg: string) => void }) {
  const [taxMethod, setTaxMethod] = useState('fifo')
  const [taxYear, setTaxYear] = useState(new Date().getFullYear())
  const [taxSymbol, setTaxSymbol] = useState('')

  const handleExportTrades = async () => {
    try {
      const blob = await reportingApi.exportTradesCSV()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `trades_${new Date().toISOString().split('T')[0]}.csv`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      showSuccess('Trades exported successfully')
    } catch (error) {
      showError('Failed to export trades: ' + (error instanceof Error ? error.message : 'Unknown error'))
    }
  }

  const handleExportPortfolio = async () => {
    try {
      const blob = await reportingApi.exportPortfolioCSV()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `portfolio_${new Date().toISOString().split('T')[0]}.csv`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      showSuccess('Portfolio exported successfully')
    } catch (error) {
      showError('Failed to export portfolio: ' + (error instanceof Error ? error.message : 'Unknown error'))
    }
  }

  const handleExportTaxReport = async () => {
    try {
      const url = `/api/reporting/tax/${taxMethod}?year=${taxYear}${taxSymbol ? `&symbol=${taxSymbol}` : ''}&paper_trading=true`
      const response = await fetch(url)
      if (!response.ok) throw new Error('Failed to generate tax report')
      const blob = await response.blob()
      const downloadUrl = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = `tax_report_${taxMethod}_${taxYear}_${new Date().toISOString().split('T')[0]}.csv`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(downloadUrl)
      document.body.removeChild(a)
      showSuccess('Tax report generated successfully')
    } catch (error) {
      showError('Failed to export tax report: ' + (error instanceof Error ? error.message : 'Unknown error'))
    }
  }

  return (
    <Grid container spacing={3}>
      {/* Export Buttons */}
      <Grid item xs={12} md={6}>
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <Description sx={{ mr: 1 }} />
              <Typography variant="h6">Export Trades</Typography>
            </Box>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              Export all trading history to CSV format.
            </Typography>
            <Button variant="contained" startIcon={<Download />} onClick={handleExportTrades} fullWidth>
              Export Trades CSV
            </Button>
          </CardContent>
        </Card>
      </Grid>

      <Grid item xs={12} md={6}>
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <Description sx={{ mr: 1 }} />
              <Typography variant="h6">Export Portfolio</Typography>
            </Box>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              Export current portfolio holdings to CSV format.
            </Typography>
            <Button variant="contained" startIcon={<Download />} onClick={handleExportPortfolio} fullWidth>
              Export Portfolio CSV
            </Button>
          </CardContent>
        </Card>
      </Grid>

      {/* Tax Reporting */}
      <Grid item xs={12}>
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>Tax Reporting</Typography>
          <Alert severity="info" sx={{ mb: 3 }}>
            Generate tax reports using FIFO or LIFO cost basis methods. Consult a tax professional for accurate reporting.
          </Alert>

          <Grid container spacing={2}>
            <Grid item xs={12} md={4}>
              <FormControl fullWidth>
                <InputLabel>Tax Method</InputLabel>
                <Select value={taxMethod} label="Tax Method" onChange={(e) => setTaxMethod(e.target.value)}>
                  <MenuItem value="fifo">FIFO (First In, First Out)</MenuItem>
                  <MenuItem value="lifo">LIFO (Last In, First Out)</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                label="Tax Year"
                type="number"
                value={taxYear}
                onChange={(e) => setTaxYear(parseInt(e.target.value) || new Date().getFullYear())}
                inputProps={{ min: 2020, max: new Date().getFullYear() }}
              />
            </Grid>
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                label="Symbol (Optional)"
                value={taxSymbol}
                onChange={(e) => setTaxSymbol(e.target.value)}
                placeholder="BTC/USD or leave empty for all"
              />
            </Grid>
            <Grid item xs={12}>
              <Button variant="contained" size="large" startIcon={<Download />} onClick={handleExportTaxReport}>
                Generate Tax Report ({taxMethod.toUpperCase()})
              </Button>
            </Grid>
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  )
}
