import { useState, useCallback, useEffect } from 'react';
import {
  Card,
  Button,
  Space,
  Typography,
  Empty,
  Input,
  Tag,
  List,
  Tooltip,
  message,
  Badge,
} from 'antd';
import {
  SearchOutlined,
  LinkOutlined,
  CopyOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  QuestionCircleOutlined,
  EditOutlined,
} from '@ant-design/icons';
import type {
  ExpertTransformationDescription,
  PatentResult,
} from '../types';
import { searchPatents } from '../services/api';

const { Text, Paragraph } = Typography;
const { TextArea } = Input;

interface PatentSearchPanelProps {
  descriptions?: ExpertTransformationDescription[];
  isDark: boolean;
}

interface SearchResultItem {
  id: string;
  query: string;
  expertName?: string;
  keyword?: string;
  loading: boolean;
  error?: string;
  totalResults: number;
  patents: PatentResult[];
}

// Get status icon and color
function getStatusDisplay(status: string | null): { icon: React.ReactNode; color: string; text: string } {
  switch (status) {
    case 'ACTIVE':
      return { icon: <CheckCircleOutlined />, color: 'green', text: 'Active' };
    case 'PENDING':
      return { icon: <ClockCircleOutlined />, color: 'blue', text: 'Pending' };
    case 'DISCONTINUED':
    case 'EXPIRED':
      return { icon: <CloseCircleOutlined />, color: 'red', text: status };
    default:
      return { icon: <QuestionCircleOutlined />, color: 'default', text: status || 'Unknown' };
  }
}

export function PatentSearchPanel({ descriptions, isDark }: PatentSearchPanelProps) {
  const [customQuery, setCustomQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchResultItem[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [apiStatus, setApiStatus] = useState<'checking' | 'connected' | 'error'>('checking');

  // Check API connection on mount
  useEffect(() => {
    const checkApi = async () => {
      try {
        const res = await fetch(`http://${window.location.hostname}:8001/health`);
        setApiStatus(res.ok ? 'connected' : 'error');
      } catch {
        setApiStatus('error');
      }
    };
    checkApi();
  }, []);

  // Search patents for a query
  const doSearch = useCallback(async (
    query: string,
    expertName?: string,
    keyword?: string
  ): Promise<SearchResultItem> => {
    const id = `search-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

    try {
      const response = await searchPatents({ query, max_results: 10 });

      return {
        id,
        query,
        expertName,
        keyword,
        loading: false,
        totalResults: response.total_results,
        patents: response.patents,
        error: response.error || undefined,
      };
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Search failed';

      return {
        id,
        query,
        expertName,
        keyword,
        loading: false,
        totalResults: 0,
        patents: [],
        error: `${errorMsg} (API: ${window.location.hostname}:8001)`,
      };
    }
  }, []);

  // Handle custom query search
  const handleSearchCustom = useCallback(async () => {
    if (!customQuery.trim()) return;

    setIsSearching(true);
    const result = await doSearch(customQuery.trim());
    setSearchResults(prev => [result, ...prev]);
    setCustomQuery('');
    setIsSearching(false);

    if (result.error) {
      message.error(`Search failed: ${result.error}`);
    } else {
      message.success(`Found ${result.totalResults.toLocaleString()} patents (${result.patents.length} returned)`);
    }
  }, [customQuery, doSearch]);

  // Handle clicking a generated description - put it in search input
  const handleSelectDescription = useCallback((desc: ExpertTransformationDescription) => {
    setCustomQuery(desc.description);
    message.info('Description loaded into search box - edit and search when ready');
  }, []);

  // Remove result from list
  const handleRemoveResult = useCallback((id: string) => {
    setSearchResults(prev => prev.filter(item => item.id !== id));
  }, []);

  // Copy patent info to clipboard
  const handleCopyPatent = useCallback((patent: PatentResult) => {
    const text = `${patent.title}\n${patent.jurisdiction}-${patent.doc_number}\n${patent.url}`;
    navigator.clipboard.writeText(text);
    message.success('Patent info copied');
  }, []);

  // Clear all results
  const handleClearAll = useCallback(() => {
    setSearchResults([]);
  }, []);

  const cardStyle: React.CSSProperties = {
    background: isDark ? '#1f1f1f' : '#fff',
  };

  return (
    <div style={{
      height: 'calc(100vh - 180px)',
      width: '100%',
      padding: 16,
      boxSizing: 'border-box',
      display: 'flex',
      flexDirection: 'row',
      gap: 16,
    }}>
        {/* Left Column - Search Input & Generated Descriptions */}
        <div style={{
          flex: '0 0 40%',
          minWidth: 0,
          display: 'flex',
          flexDirection: 'column',
          gap: 12,
          overflow: 'auto',
        }}>
            {/* Search input */}
            <Card
              size="small"
              title={
                <Space>
                  <span>Patent Search</span>
                  {apiStatus === 'checking' && <Tag color="processing">Checking...</Tag>}
                  {apiStatus === 'connected' && <Tag color="success">Connected</Tag>}
                  {apiStatus === 'error' && (
                    <Tooltip title={`Cannot reach ${window.location.hostname}:8001`}>
                      <Tag color="error">Unreachable</Tag>
                    </Tooltip>
                  )}
                </Space>
              }
              style={cardStyle}
            >
              <TextArea
                placeholder="Enter a description to search for similar patents... Click a generated description below to load it here for editing."
                value={customQuery}
                onChange={e => setCustomQuery(e.target.value)}
                onPressEnter={e => {
                  if (!e.shiftKey) {
                    e.preventDefault();
                    handleSearchCustom();
                  }
                }}
                autoSize={{ minRows: 3, maxRows: 6 }}
                style={{ marginBottom: 8 }}
                disabled={isSearching}
              />
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearchCustom}
                disabled={!customQuery.trim()}
                loading={isSearching}
                block
              >
                Search Patents
              </Button>
            </Card>

            {/* Generated Descriptions */}
            {descriptions && descriptions.length > 0 && (
              <Card
                size="small"
                title={`Generated Descriptions (${descriptions.length})`}
                style={{ ...cardStyle, flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}
                bodyStyle={{ flex: 1, overflow: 'auto', padding: 8 }}
              >
                <Space direction="vertical" style={{ width: '100%' }} size={8}>
                  {descriptions.map((desc, idx) => (
                    <div
                      key={idx}
                      onClick={() => handleSelectDescription(desc)}
                      style={{
                        padding: 8,
                        borderRadius: 4,
                        cursor: 'pointer',
                        background: isDark ? '#141414' : '#fafafa',
                        border: `1px solid ${isDark ? '#303030' : '#f0f0f0'}`,
                        transition: 'all 0.2s',
                      }}
                      onMouseEnter={e => {
                        e.currentTarget.style.borderColor = isDark ? '#177ddc' : '#1890ff';
                        e.currentTarget.style.background = isDark ? '#177ddc22' : '#1890ff11';
                      }}
                      onMouseLeave={e => {
                        e.currentTarget.style.borderColor = isDark ? '#303030' : '#f0f0f0';
                        e.currentTarget.style.background = isDark ? '#141414' : '#fafafa';
                      }}
                    >
                      <Space size={4} style={{ marginBottom: 4 }}>
                        <Tag color="blue" style={{ fontSize: 10 }}>{desc.expert_name}</Tag>
                        <Tag style={{ fontSize: 10 }}>{desc.keyword}</Tag>
                        <EditOutlined style={{ fontSize: 10, color: isDark ? '#177ddc' : '#1890ff' }} />
                      </Space>
                      <Paragraph
                        ellipsis={{ rows: 2 }}
                        style={{ marginBottom: 0, fontSize: 12 }}
                      >
                        {desc.description}
                      </Paragraph>
                    </div>
                  ))}
                </Space>
              </Card>
            )}

            {/* Empty state when no descriptions */}
            {(!descriptions || descriptions.length === 0) && (
              <Card style={{ ...cardStyle, flex: 1 }}>
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <Space direction="vertical">
                      <Text>No generated descriptions available</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        Run expert transformation first to generate descriptions
                      </Text>
                    </Space>
                  }
                />
              </Card>
            )}
        </div>

        {/* Right Column - Search Results */}
        <div style={{
          flex: 1,
          minWidth: 0,
          display: 'flex',
          flexDirection: 'column',
          overflow: 'auto',
        }}>
            <Card
              size="small"
              title={`Search Results (${searchResults.length} queries)`}
              style={{ ...cardStyle, flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}
              bodyStyle={{ flex: 1, overflow: 'auto', padding: 8 }}
              extra={
                searchResults.length > 0 && (
                  <Button size="small" danger onClick={handleClearAll}>
                    Clear All
                  </Button>
                )
              }
            >
              {searchResults.length === 0 ? (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <Space direction="vertical">
                      <Text>No search results yet</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        Enter a query or click a description to search
                      </Text>
                    </Space>
                  }
                />
              ) : (
                <Space direction="vertical" style={{ width: '100%' }} size={8}>
                  {searchResults.map(result => (
                    <Card
                      key={result.id}
                      size="small"
                      style={{ background: isDark ? '#141414' : '#fafafa' }}
                      title={
                        <Space>
                          <Text style={{ fontSize: 12, maxWidth: 300 }} ellipsis>
                            {result.query.substring(0, 60)}{result.query.length > 60 ? '...' : ''}
                          </Text>
                          <Badge
                            count={result.totalResults.toLocaleString()}
                            style={{ backgroundColor: result.error ? '#ff4d4f' : '#52c41a' }}
                            overflowCount={999999}
                          />
                        </Space>
                      }
                      extra={
                        <Button
                          type="text"
                          size="small"
                          danger
                          icon={<DeleteOutlined />}
                          onClick={() => handleRemoveResult(result.id)}
                        />
                      }
                    >
                      {result.error ? (
                        <Text type="danger">{result.error}</Text>
                      ) : result.patents.length === 0 ? (
                        <Empty
                          image={Empty.PRESENTED_IMAGE_SIMPLE}
                          description={
                            <Space direction="vertical" size={4}>
                              <Text strong>No matching patents found</Text>
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                This may indicate a novel concept with no existing prior art.
                              </Text>
                            </Space>
                          }
                        />
                      ) : (
                        <List
                          size="small"
                          dataSource={result.patents}
                          renderItem={(patent) => {
                            const status = getStatusDisplay(patent.legal_status);
                            return (
                              <List.Item
                                style={{
                                  padding: '8px',
                                  borderBottom: `1px solid ${isDark ? '#303030' : '#f0f0f0'}`,
                                }}
                                actions={[
                                  <Button
                                    key="open"
                                    type="link"
                                    size="small"
                                    icon={<LinkOutlined />}
                                    href={patent.url}
                                    target="_blank"
                                  />,
                                  <Button
                                    key="copy"
                                    type="text"
                                    size="small"
                                    icon={<CopyOutlined />}
                                    onClick={() => handleCopyPatent(patent)}
                                  />,
                                ]}
                              >
                                <List.Item.Meta
                                  title={
                                    <Space direction="vertical" size={2}>
                                      <Text strong style={{ fontSize: 13 }}>{patent.title || 'Untitled'}</Text>
                                      <Space size={4} wrap>
                                        <Tag>{patent.jurisdiction}-{patent.doc_number}</Tag>
                                        <Tag color={status.color}>{status.text}</Tag>
                                        {patent.date_published && (
                                          <Text type="secondary" style={{ fontSize: 11 }}>
                                            {patent.date_published}
                                          </Text>
                                        )}
                                      </Space>
                                    </Space>
                                  }
                                  description={
                                    patent.abstract && (
                                      <Paragraph
                                        ellipsis={{ rows: 2, expandable: true, symbol: 'more' }}
                                        style={{ marginBottom: 0, marginTop: 4, fontSize: 12 }}
                                      >
                                        {patent.abstract}
                                      </Paragraph>
                                    )
                                  }
                                />
                              </List.Item>
                            );
                          }}
                        />
                      )}
                    </Card>
                  ))}
                </Space>
              )}
            </Card>
        </div>
    </div>
  );
}
