import { useState } from 'react'
import { Box, Button, CircularProgress, Typography } from '@mui/material'
import { ArrowRight, ArrowLeft, Save } from 'lucide-react'
import { useNavigate } from 'react-router'
import { PageHeader } from '../../components/layout'
import {
  NeedBuilderProgress,
  NeedInput,
  CriteriaReviewPanel,
  FollowUpPanel,
  WeightingEditor,
  NeedCardPreview,
  NeedBuilderErrorState,
} from '../../components/demand'
import { aiService } from '../../services/aiService'
import { weightingService } from '../../services/weightingService'
import { NeedBuilderStep } from '../../domain/needBuilder'
import type { ParseNeedResult } from '../../domain/needBuilder'
import type { WeightingKey } from '../../domain/needBuilder'

export default function AISearch() {
  const navigate = useNavigate()
  const [step, setStep] = useState<typeof NeedBuilderStep[keyof typeof NeedBuilderStep]>(NeedBuilderStep.IDLE)
  const [inputText, setInputText] = useState('')
  const [parseResult, setParseResult] = useState<ParseNeedResult | null>(null)
  const [answers, setAnswers] = useState<Record<string, string>>({})
  const [weights, setWeights] = useState<Record<WeightingKey, number>>(weightingService.getDefaultWeights())
  const [error, setError] = useState<string | null>(null)

  async function handleAnalyze() {
    setStep(NeedBuilderStep.PARSING)
    setError(null)
    try {
      const resp = await aiService.parseNeed(inputText)
      const result = resp.data
      setParseResult(result)
      setWeights(result.suggestedWeights as Record<WeightingKey, number>)
      setStep(NeedBuilderStep.PARSED_REQUIRES_REVIEW)
    } catch {
      setError('Die KI-Analyse ist fehlgeschlagen. Bitte versuchen Sie es erneut.')
      setStep(NeedBuilderStep.ERROR)
    }
  }

  function handleAnswer(id: string, ans: string) {
    setAnswers(prev => ({ ...prev, [id]: ans }))
  }

  function handleContinueToWeighting() {
    setStep(NeedBuilderStep.WEIGHTING_REVIEW)
  }

  function handleContinueToSave() {
    setStep(NeedBuilderStep.READY_TO_SAVE)
  }

  async function handleSave() {
    setStep(NeedBuilderStep.SAVING)
    await new Promise(r => setTimeout(r, 800))
    navigate('/demand/results', { state: { fromNeedBuilder: true } })
  }

  function handleRetry() {
    setStep(NeedBuilderStep.IDLE)
    setError(null)
    setParseResult(null)
  }

  const isReview = step === NeedBuilderStep.PARSED_REQUIRES_REVIEW || step === NeedBuilderStep.CLARIFICATION_REQUIRED
  const isSaveStep = step === NeedBuilderStep.READY_TO_SAVE || step === NeedBuilderStep.SAVING

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <PageHeader
        title="AI Bedarfsanalyse"
        subtitle="Beschreiben Sie Ihren Flächenbedarf in natürlicher Sprache"
      />
      <NeedBuilderProgress step={step} />

      <Box sx={{ flex: 1, overflowY: 'auto', px: 3, py: 3 }}>
        {/* Step: Input */}
        {step === NeedBuilderStep.IDLE && (
          <NeedInput value={inputText} onChange={setInputText} onSubmit={handleAnalyze} />
        )}

        {/* Step: Parsing */}
        {step === NeedBuilderStep.PARSING && (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', py: 16, gap: 3 }}>
            <CircularProgress size={48} sx={{ color: '#1e3a5f' }} />
            <Typography variant="h6" color="text.secondary">
              KI analysiert Ihren Bedarf…
            </Typography>
            <Typography variant="caption" color="text.secondary">
              Kriterien werden extrahiert und bewertet
            </Typography>
          </Box>
        )}

        {/* Step: Criteria Review + Follow-up */}
        {isReview && parseResult && (
          <Box>
            <Box className="grid grid-cols-2 gap-4" sx={{ mb: 2 }}>
              <CriteriaReviewPanel result={parseResult} />
              <FollowUpPanel
                questions={parseResult.followUpQuestionCandidates}
                answers={answers}
                onAnswer={handleAnswer}
                onContinue={handleContinueToWeighting}
              />
            </Box>
            <Box sx={{ display: 'flex', justifyContent: 'flex-start' }}>
              <Button
                variant="outlined"
                startIcon={<ArrowLeft size={16} />}
                onClick={() => setStep(NeedBuilderStep.IDLE)}
              >
                Neu eingeben
              </Button>
            </Box>
          </Box>
        )}

        {/* Step: Weighting */}
        {step === NeedBuilderStep.WEIGHTING_REVIEW && (
          <Box>
            <WeightingEditor
              weights={weights}
              onChange={setWeights}
              assetType={parseResult?.extractedCriteria.assetType}
            />
            <Box sx={{ maxWidth: 720, mx: 'auto', display: 'flex', justifyContent: 'space-between', mt: 3 }}>
              <Button
                variant="outlined"
                startIcon={<ArrowLeft size={16} />}
                onClick={() => setStep(NeedBuilderStep.PARSED_REQUIRES_REVIEW)}
              >
                Zurück
              </Button>
              <Button
                variant="contained"
                endIcon={<ArrowRight size={16} />}
                onClick={handleContinueToSave}
                sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}
              >
                Vorschau & Speichern
              </Button>
            </Box>
          </Box>
        )}

        {/* Step: Preview + Save */}
        {isSaveStep && parseResult && (
          <Box>
            <NeedCardPreview criteria={parseResult.extractedCriteria} weights={weights} />
            <Box sx={{ maxWidth: 720, mx: 'auto', display: 'flex', justifyContent: 'space-between', mt: 3 }}>
              <Button
                variant="outlined"
                startIcon={<ArrowLeft size={16} />}
                onClick={() => setStep(NeedBuilderStep.WEIGHTING_REVIEW)}
                disabled={step === NeedBuilderStep.SAVING}
              >
                Zurück
              </Button>
              <Button
                variant="contained"
                onClick={handleSave}
                disabled={step === NeedBuilderStep.SAVING}
                endIcon={
                  step === NeedBuilderStep.SAVING
                    ? <CircularProgress size={16} color="inherit" />
                    : <Save size={16} />
                }
                sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}
              >
                {step === NeedBuilderStep.SAVING ? 'Wird gespeichert…' : 'Bedarf speichern & Suche starten'}
              </Button>
            </Box>
          </Box>
        )}

        {/* Step: Error */}
        {step === NeedBuilderStep.ERROR && (
          <NeedBuilderErrorState
            message={error ?? 'Unbekannter Fehler'}
            onRetry={handleRetry}
          />
        )}
      </Box>
    </Box>
  )
}
