'use client';

import { useState } from 'react';
import { Box, Paper, Typography, TextField, Button } from '@mui/material';
import { MessageSquare, Search } from 'lucide-react';
import { ragService } from '../services/rag-service';

export default function ChatBot() {
  const [searchQuery, setSearchQuery] = useState('');
  const [chatResponse, setChatResponse] = useState<any>(null);

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    console.log(`[PatchPilot] RAG Search gestartet: "${searchQuery}"`);
    const res = await ragService.search(searchQuery);
    console.log(`[PatchPilot] RAG Antwort erhalten:`, res);
    setChatResponse(res);
  };

  return (
    <Paper sx={{ p: 3, mb: 4, background: '#F3EDF7', borderRadius: 3 }}>
      <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', fontWeight: 'bold' }}>
        <MessageSquare size={20} style={{ marginRight: 8 }} /> Reparatur-Assistent (RAG)
      </Typography>
      <Box sx={{ display: 'flex', gap: 1 }}>
        <TextField 
          fullWidth placeholder="Was möchtest du reparieren?" 
          variant="outlined" size="small"
          value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
          sx={{ bgcolor: 'white', borderRadius: 1 }}
        />
        <Button 
          variant="contained" 
          onClick={handleSearch} 
          startIcon={<Search size={18} />}
          sx={{ borderRadius: 2 }}
        >
          Fragen
        </Button>
      </Box>
      {chatResponse && (
        <Box sx={{ mt: 2, p: 2, bgcolor: 'white', borderRadius: 2, borderLeft: '4px solid #6750A4' }}>
          <Typography variant="body1">{chatResponse.answer}</Typography>
          {chatResponse.sources.length > 0 && (
            <Typography variant="caption" sx={{ display: 'block', mt: 1, color: 'gray', fontStyle: 'italic' }}>
              Quelle: {chatResponse.sources.join(', ')}
            </Typography>
          )}
        </Box>
      )}
    </Paper>
  );
}
