import { useState } from 'react'
import {
  Box, Button, Chip, CircularProgress, Divider, Tooltip, Typography,
} from '@mui/material'
import {
  Plug2, FileSpreadsheet, Upload, Globe, Rss,
  Database, FileText, PenLine, Bot,
  Play, Pause, Scale, RefreshCw, ExternalLink,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import type { DataSource, ConnectorRun } from '../../domain/dataSource'
import {
  DATA_SOURCE_TYPE_LABELS,
  SourceStatus,
  TermsStatus,
} from '../../domain/dataSource'
import { FreshnessBadge } from '../badges/FreshnessBadge'
import { SourceHealthBadge } from './SourceHealthBadge'
import { TermsStatusBadge } from './TermsStatusBadge'
import { ReliabilityScorePanel } from './ReliabilityScorePanel'
import { DataCategoryBadgeList } from './DataCategoryBadgeList'
import { SourceErrorPanel } from './SourceErrorPanel'
import { ConnectorRunTable } from './ConnectorRunTable'
import { ConnectorRunDetailDrawer } from './ConnectorRunDetailDrawer'
import { MarketSignalEmptyState } from './MarketSignalEmptyState'
import {
  useConnectorRuns,
  useTriggerMockRun,
  useUpdateSourceStatus,
  useMarkTermsStatus,
} from '../../hooks/useDataSources'

const TYPE_ICONS: Record<string, LucideIcon> = {
  API_CONNECTOR: Plug2,
  CSV_IMPORT: FileSpreadsheet,
  MANUAL_UPLOAD: Upload,
  PUBLIC_WEB_SOURCE: Globe,
  PARTNER_FEED: Rss,
  INTERNAL_PORTFOLIO_EXPORT: Database,
  CONTRACT_METADATA_IMPORT: FileText,
  ANALYST_ENTRY: PenLine,
  FUTURE_CRAWLER_STUB: Bot,
}

function formatDate(iso?: string): string {
  if (!iso) return '—'
  return new Date(iso).toLocaleString('de-CH', {
    day: '2-digit', month: '2-digit', year: '2-digit',
    hour: '2-digit', minute: '2-digit',
  })
}

interface SourceDetailPanelProps {
  source: DataSource | null
}

export function SourceDetailPanel({ source }: SourceDetailPanelProps) {
  const [selectedRun, setSelectedRun] = useState<ConnectorRun | null>(null)

  const { data: runs = [] } = useConnectorRuns(source?.id ?? null)
  const { mutate: triggerRun, isPending: isRunning } = useTriggerMockRun()
  const { mutate: updateStatus, isPending: isUpdating } = useUpdateSourceStatus()
  const { mutate: markTerms, isPending: isMarkingTerms } = useMarkTermsStatus()

  if (!source) return <MarketSignalEmptyState variant="not-found" />

  const SourceIcon = TYPE_ICONS[source.sourceType] ?? Database
  const isActionable = source.status !== SourceStatus.DISABLED
  const RUN_ELIGIBLE: SourceStatus[] = [SourceStatus.ACTIVE, SourceStatus.ERROR]
  const canRun = RUN_ELIGIBLE.includes(source.status)

  return (
    <Box sx={{ height: '100%', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <Box sx={{ p: 3, borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5, mb: 1.5 }}>
          <Box
            sx={{
              width: 36,
              height: 36,
              borderRadius: 1.5,
              bgcolor: 'rgba(30,58,95,0.08)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
            }}
          >
            <SourceIcon size={18} color="#1e3a5f" />
          </Box>
          <Box sx={{ flex: 1 }}>
            <Typography variant="h6" sx={{ fontWeight: 600, lineHeight: 1.3, mb: 0.25 }}>
              {source.name}
            </Typography>
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              {DATA_SOURCE_TYPE_LABELS[source.sourceType]}
              {source.ownerOrganizationId && ` · Org ${source.ownerOrganizationId}`}
            </Typography>
          </Box>
        </Box>

        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75 }}>
          <SourceHealthBadge status={source.status} />
          <TermsStatusBadge status={source.termsStatus} />
          <FreshnessBadge status={source.freshnessStatus} />
        </Box>
      </Box>

      {/* Body */}
      <Box sx={{ p: 3, flex: 1 }}>
        {source.errorState && <SourceErrorPanel errorState={source.errorState} />}

        {/* Legal basis */}
        <Box sx={{ p: 2, bgcolor: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 1, mb: 2 }}>
          <Typography variant="caption" sx={{ color: '#64748b', fontWeight: 600, display: 'block', mb: 0.25 }}>
            Rechtliche Grundlage
          </Typography>
          <Typography variant="body2" sx={{ color: '#1e293b', lineHeight: 1.5 }}>
            {source.legalBasis}
          </Typography>
        </Box>

        {/* Reliability */}
        <Box sx={{ mb: 2 }}>
          <ReliabilityScorePanel score={source.reliabilityScore} />
        </Box>

        {/* Run timestamps */}
        <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
          <Box>
            <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>Letzter Run</Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>{formatDate(source.lastRunAt)}</Typography>
          </Box>
          <Box>
            <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>Nächster Run</Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>{formatDate(source.nextRunAt)}</Typography>
          </Box>
        </Box>

        <Divider sx={{ mb: 2 }} />

        {/* Data categories */}
        <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1 }}>Datenkategorien</Typography>
        <Box sx={{ mb: 2 }}>
          <DataCategoryBadgeList categories={source.dataCategories} />
        </Box>

        {/* Region coverage */}
        <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.75 }}>Regionen</Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mb: 2 }}>
          {source.regionCoverage.map((r) => (
            <Chip
              key={r}
              size="small"
              label={r}
              sx={{ bgcolor: 'transparent', border: '1px solid #e2e8f0', color: '#475569', fontSize: '0.72rem' }}
            />
          ))}
        </Box>

        {/* Asset types */}
        <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.75 }}>Asset-Typen</Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mb: 2 }}>
          {source.supportedAssetTypes.map((a) => (
            <Chip
              key={a}
              size="small"
              label={a}
              sx={{ bgcolor: 'rgba(30,58,95,0.06)', color: '#1e3a5f', border: 'none', fontSize: '0.72rem' }}
            />
          ))}
        </Box>

        {source.notes && (
          <>
            <Divider sx={{ mb: 2 }} />
            <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 0.5 }}>Notizen</Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary', fontStyle: 'italic', lineHeight: 1.5, mb: 2 }}>
              {source.notes}
            </Typography>
          </>
        )}

        {/* Actions */}
        {isActionable && (
          <>
            <Divider sx={{ mb: 2 }} />
            <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1.5 }}>Aktionen</Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
              {canRun && (
                <Button
                  size="small"
                  variant="contained"
                  startIcon={isRunning ? <CircularProgress size={12} sx={{ color: '#fff' }} /> : <Play size={14} />}
                  disabled={isRunning}
                  onClick={() => triggerRun(source.id)}
                  sx={{ bgcolor: '#1e3a5f', textTransform: 'none', fontSize: '0.8rem', '&:hover': { bgcolor: '#162d4a' } }}
                >
                  {isRunning ? 'Läuft...' : 'Demo-Run starten'}
                </Button>
              )}
              {source.status === SourceStatus.ACTIVE && (
                <Button
                  size="small"
                  variant="outlined"
                  startIcon={<Pause size={14} />}
                  disabled={isUpdating}
                  onClick={() => updateStatus({ id: source.id, status: SourceStatus.PAUSED })}
                  sx={{ textTransform: 'none', fontSize: '0.8rem', borderColor: '#a16207', color: '#a16207', '&:hover': { borderColor: '#854d0e', bgcolor: 'rgba(161,98,7,0.04)' } }}
                >
                  Pausieren
                </Button>
              )}
              {source.status === SourceStatus.PAUSED && (
                <Button
                  size="small"
                  variant="outlined"
                  startIcon={<RefreshCw size={14} />}
                  disabled={isUpdating}
                  onClick={() => updateStatus({ id: source.id, status: SourceStatus.ACTIVE })}
                  sx={{ textTransform: 'none', fontSize: '0.8rem', borderColor: '#15803d', color: '#15803d', '&:hover': { borderColor: '#166534', bgcolor: 'rgba(21,128,61,0.04)' } }}
                >
                  Reaktivieren
                </Button>
              )}
              {source.termsStatus !== TermsStatus.NEEDS_LEGAL_REVIEW && (
                <Tooltip title="Rechtliche Prüfung anfordern">
                  <Button
                    size="small"
                    variant="outlined"
                    startIcon={<Scale size={14} />}
                    disabled={isMarkingTerms}
                    onClick={() => markTerms({ id: source.id, termsStatus: TermsStatus.NEEDS_LEGAL_REVIEW })}
                    sx={{ textTransform: 'none', fontSize: '0.8rem', color: 'text.secondary', borderColor: 'divider' }}
                  >
                    Rechtsprüfung anfordern
                  </Button>
                </Tooltip>
              )}
              <Tooltip title="Generierte Signale ansehen (Demo)">
                <Button
                  size="small"
                  variant="outlined"
                  startIcon={<ExternalLink size={14} />}
                  sx={{ textTransform: 'none', fontSize: '0.8rem', color: 'text.secondary', borderColor: 'divider' }}
                >
                  Signale ansehen
                </Button>
              </Tooltip>
            </Box>
          </>
        )}

        {/* Connector runs */}
        <Divider sx={{ mb: 2 }} />
        <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1.5 }}>
          Import-Runs
        </Typography>
        <ConnectorRunTable runs={runs} onSelectRun={setSelectedRun} />
      </Box>

      <ConnectorRunDetailDrawer run={selectedRun} onClose={() => setSelectedRun(null)} />
    </Box>
  )
}
