import {
  useState,
  useEffect,
  Card,
  Button,
  Space,
  message,
  Row,
  Col,
  Select,
  Input,
  Tag,
  Badge,
  RobotOutlined,
  ReloadOutlined,
  FilterOutlined,
  SearchOutlined,
  PlusOutlined,
  aiSuggestionDataSource,
  Option,
  FC,
} from '@/imports';
import type { AISuggestion } from '../services/aiSuggestionDataSource';
import AISuggestionDisplay from '../components/ai-suggestion/AISuggestionDisplay';

const AISuggestionPage: FC = () => {
  const [suggestions, setSuggestions] = useState<AISuggestion[]>([]);
  const [selectedSuggestion, setSelectedSuggestion] = useState<AISuggestion | null>(null);
  const [filterType, setFilterType] = useState<string>('');
  const [filterPriority, setFilterPriority] = useState<string>('');
  const [searchText, setSearchText] = useState<string>('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchSuggestions();
  }, [filterType, filterPriority, searchText]);

  const fetchSuggestions = async () => {
    setLoading(true);
    try {
      const data = await aiSuggestionDataSource.fetchSuggestions({
        type: filterType || undefined,
        priority: filterPriority || undefined,
        search: searchText || undefined,
      });
      setSuggestions(data);
      if (data.length > 0 && !selectedSuggestion) {
        setSelectedSuggestion(data[0]);
      }
    } catch (error) {
      message.error('Failed to load suggestions');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async () => {
    if (selectedSuggestion) {
      setLoading(true);
      try {
        await aiSuggestionDataSource.approveSuggestion(selectedSuggestion.id);
        message.success('Suggestion approved!');
        fetchSuggestions();
      } catch (error) {
        message.error('Failed to approve suggestion');
      } finally {
        setLoading(false);
      }
    }
  };

  const handleReject = async () => {
    if (selectedSuggestion) {
      setLoading(true);
      try {
        await aiSuggestionDataSource.rejectSuggestion(selectedSuggestion.id);
        message.error('Suggestion rejected!');
        fetchSuggestions();
      } catch (error) {
        message.error('Failed to reject suggestion');
      } finally {
        setLoading(false);
      }
    }
  };

  const handleModify = () => {
    message.info('Modify suggestion clicked!');
  };

  const handleSelectSuggestion = (suggestion: AISuggestion) => {
    setSelectedSuggestion(suggestion);
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleFilter = (field: string, value: string) => {
    if (field === 'type') setFilterType(value);
    if (field === 'priority') setFilterPriority(value);
  };

  const getFilteredSuggestions = () => {
    return suggestions;
  };

  return (
    <div className="ai-suggestion-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={16}>
          <Card
            title={
              <Space size="middle">
                <RobotOutlined style={{ color: '#1890ff' }} />
                <span>AI Suggestions</span>
              </Space>
            }
            extra={
              <Button icon={<ReloadOutlined />}>
                Refresh
              </Button>
            }
          >
            <Row gutter={16} style={{ marginBottom: 16 }}>
              <Col span={8}>
                <Input
                  placeholder="Search suggestions"
                  prefix={<SearchOutlined />}
                  value={searchText}
                  onChange={(e) => handleSearch(e.target.value)}
                  allowClear
                />
              </Col>
              <Col span={6}>
                <Select
                  placeholder="Filter by type"
                  value={filterType}
                  onChange={(value) => handleFilter('type', value)}
                  allowClear
                  style={{ width: '100%' }}
                >
                  <Option value="Pricing Optimization">Pricing Optimization</Option>
                  <Option value="Inventory Management">Inventory Management</Option>
                  <Option value="Marketing Campaign">Marketing Campaign</Option>
                </Select>
              </Col>
              <Col span={6}>
                <Select
                  placeholder="Filter by priority"
                  value={filterPriority}
                  onChange={(value) => handleFilter('priority', value)}
                  allowClear
                  style={{ width: '100%' }}
                >
                  <Option value="low">Low</Option>
                  <Option value="medium">Medium</Option>
                  <Option value="high">High</Option>
                  <Option value="urgent">Urgent</Option>
                </Select>
              </Col>
              <Col span={4}>
                <Button type="primary" icon={<PlusOutlined />} block>
                  New Suggestion
                </Button>
              </Col>
            </Row>
            <div style={{ maxHeight: 600, overflowY: 'auto' }}>
              {getFilteredSuggestions().map((suggestion) => (
                <Card
                  key={suggestion.id}
                  onClick={() => handleSelectSuggestion(suggestion)}
                  style={{
                    marginBottom: 16,
                    cursor: 'pointer',
                    border: selectedSuggestion?.id === suggestion.id ? '2px solid #1890ff' : '1px solid #f0f0f0',
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Space size="middle">
                      <Tag color={suggestion.type === 'Pricing Optimization' ? 'blue' : suggestion.type === 'Inventory Management' ? 'green' : 'orange'}>
                        {suggestion.type}
                      </Tag>
                      <Badge
                        status={suggestion.priority === 'urgent' ? 'error' : suggestion.priority === 'high' ? 'warning' : 'default'}
                        text={suggestion.priority}
                      />
                    </Space>
                    <Space size="middle">
                      <Tag color="default">Confidence: {suggestion.confidence}%</Tag>
                    </Space>
                  </div>
                  <h3 style={{ marginTop: 8, marginBottom: 4 }}>{suggestion.title}</h3>
                  <p style={{ marginBottom: 8, color: '#666' }}>{suggestion.description.substring(0, 100)}...</p>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Space size="small">
                      {suggestion.dataSources.map((source) => (
                        <Tag key={source}>{source}</Tag>
                      ))}
                    </Space>
                    <span style={{ fontSize: 12, color: '#999' }}>{suggestion.updatedAt}</span>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </Col>
        <Col span={8}>
          {selectedSuggestion && (
            <AISuggestionDisplay
              suggestion={selectedSuggestion}
              onApprove={handleApprove}
              onReject={handleReject}
              onModify={handleModify}
            />
          )}
        </Col>
      </Row>
    </div>
  );
};

export default AISuggestionPage;
