import { Alert, Box, Button, CircularProgress, Divider, Typography } from '@mui/material'
import { Rocket } from 'lucide-react'
import type { MarketSignal } from '../../domain/marketSignal'
import { GateStatus } from '../../domain/signalPipeline'
import {
  useSignalPipelineState,
  useSignalAuditTrail,
  usePublishToFutureAvailability,
} from '../../hooks/useSignalPipeline'
import { FeedEligibilityBadge } from './FeedEligibilityBadge'
import { SignalPipelineStepper } from './SignalPipelineStepper'
import { EvidenceGatePanel } from './EvidenceGatePanel'
import { ConfidenceGatePanel } from './ConfidenceGatePanel'
import { SensitivityGatePanel } from './SensitivityGatePanel'
import { ReviewGatePanel } from './ReviewGatePanel'
import { MatchabilityGatePanel } from './MatchabilityGatePanel'
import { SignalToMatchAuditTrail } from './SignalToMatchAuditTrail'

interface SignalPipelineViewProps {
  signal: MarketSignal
}

export function SignalPipelineView({ signal }: SignalPipelineViewProps) {
  const { data: pipelineState, isLoading: isLoadingPipeline } = useSignalPipelineState(signal.id)
  const { data: auditTrail = [], isLoading: isLoadingAudit } = useSignalAuditTrail(signal.id)
  const { mutate: publish, isPending: isPublishing } = usePublishToFutureAvailability()

  const canPublish =
    pipelineState !== null &&
    pipelineState !== undefined &&
    pipelineState.gates.REVIEW_GATE.status === GateStatus.PASSED &&
    !pipelineState.publishedToFutureAvailability

  return (
    <Box sx={{ height: '100%', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <Box sx={{ p: 3, borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
        <Typography variant="h6" sx={{ fontWeight: 600, lineHeight: 1.3, mb: 1 }}>
          {signal.title}
        </Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>
          <FeedEligibilityBadge signal={signal} />
          {pipelineState?.feedDisclaimer && (
            <Typography
              variant="caption"
              sx={{
                color: '#a16207',
                bgcolor: 'rgba(234,179,8,0.08)',
                px: 1,
                py: 0.25,
                borderRadius: 1,
                border: '1px solid rgba(234,179,8,0.2)',
                lineHeight: 1.4,
              }}
            >
              {pipelineState.feedDisclaimer}
            </Typography>
          )}
        </Box>
      </Box>

      {/* Pipeline Stepper */}
      <Box sx={{ p: 3, borderBottom: '1px solid #e2e8f0', flexShrink: 0, bgcolor: '#fafafa' }}>
        {isLoadingPipeline && (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
            <CircularProgress size={20} />
          </Box>
        )}
        {pipelineState && <SignalPipelineStepper pipelineState={pipelineState} />}
      </Box>

      {/* Gate panels */}
      <Box sx={{ p: 3, flex: 1 }}>
        {isLoadingPipeline && !pipelineState && (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <CircularProgress size={24} />
          </Box>
        )}

        {pipelineState && (
          <>
            <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1.5 }}>
              Gate-Bewertungen
            </Typography>

            <EvidenceGatePanel gate={pipelineState.gates.EVIDENCE_GATE} />
            <ConfidenceGatePanel gate={pipelineState.gates.CONFIDENCE_GATE} />
            <SensitivityGatePanel gate={pipelineState.gates.SENSITIVITY_GATE} />
            <ReviewGatePanel gate={pipelineState.gates.REVIEW_GATE} />
            <MatchabilityGatePanel gate={pipelineState.gates.MATCHABILITY_GATE} />

            {/* Feed eligibility summary */}
            {pipelineState.overallEligible && pipelineState.publishedToFutureAvailability && (
              <Alert
                severity="success"
                sx={{ mb: 2, fontSize: '0.8rem' }}
              >
                Signal ist im Future Availability Feed publiziert
                {pipelineState.publishedAt && (
                  <> · {new Date(pipelineState.publishedAt).toLocaleString('de-CH', {
                    day: '2-digit', month: '2-digit', year: '2-digit',
                    hour: '2-digit', minute: '2-digit',
                  })}</>
                )}
              </Alert>
            )}

            {pipelineState.overallEligible && !pipelineState.publishedToFutureAvailability && (
              <Alert severity="info" sx={{ mb: 2, fontSize: '0.8rem' }}>
                Signal ist feed-fähig – noch nicht publiziert.
              </Alert>
            )}

            {/* Publish button */}
            {canPublish && (
              <Box sx={{ mb: 2 }}>
                <Button
                  variant="contained"
                  size="small"
                  startIcon={isPublishing ? <CircularProgress size={14} color="inherit" /> : <Rocket size={14} />}
                  disabled={isPublishing}
                  onClick={() => publish(signal.id)}
                  sx={{
                    textTransform: 'none',
                    fontSize: '0.8rem',
                    bgcolor: '#152642',
                    '&:hover': { bgcolor: '#162d4a' },
                  }}
                >
                  In Future Availability publizieren
                </Button>
              </Box>
            )}

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

            <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1.5 }}>
              Audit Trail
            </Typography>
            {isLoadingAudit ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
                <CircularProgress size={16} />
              </Box>
            ) : (
              <SignalToMatchAuditTrail entries={auditTrail} />
            )}
          </>
        )}
      </Box>
    </Box>
  )
}
