import { useState, useEffect, useCallback } from 'react';
import { useOutletContext } from 'react-router-dom';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  DatePicker,
  Drawer,
  Typography,
  Popconfirm,
  message,
  Statistic,
  Row,
  Col,
  Tabs,
  Form,
  Descriptions,
  Grid,
} from 'antd';
import {
  CheckCircleOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  WarningOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { mediaApi } from '@/lib/media-api';
import type { AppOutletContext } from '@/types/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

interface CommentRecord {
  id: number;
  mediaId: number;
  videoTitle: string;
  content: string;
  createdAt: string;
  safetyStatus: string | null;
  safetyCategories: any;
  safetyReasoning: string | null;
  isHidden: boolean | null;
  hiddenAt: string | null;
  hiddenReason: string | null;
  moderationNotes: string | null;
  user: { id: string; name: string; email: string } | null;
  moderation: {
    id: number;
    status: string;
    moderatedAt: string | null;
    reason: string | null;
    moderator: { id: string; name: string | null } | null;
  } | null;
}

interface CommentStats {
  total: number;
  pending: number;
  flagged: number;
  hidden: number;
  safe: number;
}

interface WordFilter {
  id: number;
  word: string;
  level: string;
  createdAt: string;
  creator: { id: string; name: string | null } | null;
}

export default function CommentModerationPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();

  useEffect(() => {
    setPageHeader({ title: 'Comment Moderation' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  // Comments state
  const [comments, setComments] = useState<CommentRecord[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [stats, setStats] = useState<CommentStats>({ total: 0, pending: 0, flagged: 0, hidden: 0, safe: 0 });
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize] = useState(20);

  // Filters
  const [statusFilter, setStatusFilter] = useState<string | undefined>(undefined);
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);

  // Detail drawer
  const [selectedComment, setSelectedComment] = useState<CommentRecord | null>(null);
  const [notesInput, setNotesInput] = useState('');
  const [savingNotes, setSavingNotes] = useState(false);

  // Word filters
  const [wordFilters, setWordFilters] = useState<WordFilter[]>([]);
  const [wordFiltersLoading, setWordFiltersLoading] = useState(false);
  const [newWord, setNewWord] = useState('');
  const [newWordLevel, setNewWordLevel] = useState<string>('medium');

  // Fetch stats
  const fetchStats = useCallback(async () => {
    try {
      const { data } = await mediaApi.get('/media/admin/comments/stats');
      setStats(data);
    } catch {
      // silent
    }
  }, []);

  // Fetch comments
  const fetchComments = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { page, limit: pageSize };
      if (statusFilter) params.status = statusFilter;
      if (searchText) params.search = searchText;
      if (dateRange) {
        params.dateFrom = dateRange[0].startOf('day').toISOString();
        params.dateTo = dateRange[1].endOf('day').toISOString();
      }

      const { data } = await mediaApi.get('/media/admin/comments', { params });
      setComments(data.comments);
      setTotal(data.total);
    } catch {
      message.error('Failed to load comments');
    } finally {
      setLoading(false);
    }
  }, [page, pageSize, statusFilter, searchText, dateRange]);

  // Fetch word filters
  const fetchWordFilters = useCallback(async () => {
    setWordFiltersLoading(true);
    try {
      const { data } = await mediaApi.get('/media/admin/word-filters');
      setWordFilters(data.words);
    } catch {
      message.error('Failed to load word filters');
    } finally {
      setWordFiltersLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchComments();
    fetchStats();
  }, [fetchComments, fetchStats]);

  // Actions
  const handleApprove = async (id: number) => {
    try {
      await mediaApi.patch(`/media/admin/comments/${id}/approve`);
      message.success('Comment approved');
      fetchComments();
      fetchStats();
    } catch {
      message.error('Failed to approve comment');
    }
  };

  const handleHide = async (id: number, reason: string = 'manual') => {
    try {
      await mediaApi.patch(`/media/admin/comments/${id}/hide`, { reason });
      message.success('Comment hidden');
      fetchComments();
      fetchStats();
    } catch {
      message.error('Failed to hide comment');
    }
  };

  const handleUnhide = async (id: number) => {
    try {
      await mediaApi.patch(`/media/admin/comments/${id}/unhide`);
      message.success('Comment unhidden');
      fetchComments();
      fetchStats();
    } catch {
      message.error('Failed to unhide comment');
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await mediaApi.delete(`/media/admin/comments/${id}`);
      message.success('Comment deleted');
      fetchComments();
      fetchStats();
      if (selectedComment?.id === id) setSelectedComment(null);
    } catch {
      message.error('Failed to delete comment');
    }
  };

  const handleSaveNotes = async () => {
    if (!selectedComment) return;
    setSavingNotes(true);
    try {
      await mediaApi.put(`/media/admin/comments/${selectedComment.id}/notes`, { notes: notesInput });
      message.success('Notes saved');
      setSelectedComment({ ...selectedComment, moderationNotes: notesInput });
      fetchComments();
    } catch {
      message.error('Failed to save notes');
    } finally {
      setSavingNotes(false);
    }
  };

  // Word filter actions
  const handleAddWord = async () => {
    if (!newWord.trim()) return;
    try {
      await mediaApi.post('/media/admin/word-filters', { word: newWord.trim(), level: newWordLevel });
      message.success('Word added to filter');
      setNewWord('');
      fetchWordFilters();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to add word'));
    }
  };

  const handleDeleteWord = async (id: number) => {
    try {
      await mediaApi.delete(`/media/admin/word-filters/${id}`);
      message.success('Word removed from filter');
      fetchWordFilters();
    } catch {
      message.error('Failed to remove word');
    }
  };

  // Status tag renderer
  const renderStatusTag = (record: CommentRecord) => {
    if (record.isHidden) {
      return <Tag color="error" icon={<EyeInvisibleOutlined />}>Hidden</Tag>;
    }
    switch (record.safetyStatus) {
      case 'safe':
        return <Tag color="success" icon={<CheckCircleOutlined />}>Safe</Tag>;
      case 'flagged':
        return <Tag color="warning" icon={<WarningOutlined />}>Flagged</Tag>;
      case 'pending':
      default:
        return <Tag color="default">Pending</Tag>;
    }
  };

  // Table columns
  const columns: ColumnsType<CommentRecord> = [
    {
      title: 'Content',
      dataIndex: 'content',
      width: 300,
      ellipsis: true,
      render: (text: string, record) => (
        <Button type="link" onClick={() => { setSelectedComment(record); setNotesInput(record.moderationNotes || ''); }} style={{ padding: 0, textAlign: 'left', whiteSpace: 'normal', height: 'auto' }}>
          <Text ellipsis style={{ maxWidth: 280 }}>{text}</Text>
        </Button>
      ),
    },
    {
      title: 'Video',
      dataIndex: 'videoTitle',
      width: 150,
      ellipsis: true,
    },
    {
      title: 'User',
      dataIndex: 'user',
      width: 120,
      render: (user: CommentRecord['user']) => user?.name || <Text type="secondary">Anonymous</Text>,
    },
    {
      title: 'Status',
      width: 110,
      render: (_: any, record) => renderStatusTag(record),
    },
    {
      title: 'Date',
      dataIndex: 'createdAt',
      width: 140,
      render: (date: string) => dayjs(date).format('MMM D, HH:mm'),
    },
    {
      title: 'Actions',
      width: 180,
      render: (_: any, record) => (
        <Space size={4}>
          {record.safetyStatus !== 'safe' && !record.isHidden && (
            <Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(record.id)}>
              Approve
            </Button>
          )}
          {!record.isHidden ? (
            <Button size="small" danger icon={<EyeInvisibleOutlined />} onClick={() => handleHide(record.id)}>
              Hide
            </Button>
          ) : (
            <Button size="small" icon={<EyeOutlined />} onClick={() => handleUnhide(record.id)}>
              Unhide
            </Button>
          )}
          <Popconfirm title="Permanently delete this comment?" onConfirm={() => handleDelete(record.id)} okText="Delete" okType="danger">
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // Word filter columns
  const wordFilterColumns: ColumnsType<WordFilter> = [
    { title: 'Word', dataIndex: 'word', width: 200 },
    {
      title: 'Level',
      dataIndex: 'level',
      width: 120,
      render: (level: string) => {
        const colors: Record<string, string> = { high: 'error', medium: 'warning', low: 'blue', custom: 'default' };
        return <Tag color={colors[level] || 'default'}>{level.toUpperCase()}</Tag>;
      },
    },
    {
      title: 'Added By',
      width: 120,
      render: (_: any, record) => record.creator?.name || <Text type="secondary">System</Text>,
    },
    {
      title: 'Date',
      dataIndex: 'createdAt',
      width: 140,
      render: (date: string) => dayjs(date).format('MMM D, YYYY'),
    },
    {
      title: '',
      width: 60,
      render: (_: any, record) => (
        <Popconfirm title="Remove this word?" onConfirm={() => handleDeleteWord(record.id)}>
          <Button size="small" danger icon={<DeleteOutlined />} />
        </Popconfirm>
      ),
    },
  ];

  return (
    <div>
      <Tabs
        defaultActiveKey="comments"
        items={[
          {
            key: 'comments',
            label: 'Comments',
            children: (
              <>
                {/* Stats Cards */}
                <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                  <Col xs={12} sm={6}>
                    <Card size="small"><Statistic title="Total" value={stats.total} /></Card>
                  </Col>
                  <Col xs={12} sm={6}>
                    <Card size="small"><Statistic title="Pending" value={stats.pending} valueStyle={{ color: '#bfbfbf' }} /></Card>
                  </Col>
                  <Col xs={12} sm={6}>
                    <Card size="small"><Statistic title="Flagged" value={stats.flagged} valueStyle={{ color: '#faad14' }} /></Card>
                  </Col>
                  <Col xs={12} sm={6}>
                    <Card size="small"><Statistic title="Hidden" value={stats.hidden} valueStyle={{ color: '#ff4d4f' }} /></Card>
                  </Col>
                </Row>

                {/* Filter Bar */}
                <Card size="small" style={{ marginBottom: 16 }}>
                  <Space wrap>
                    <Select
                      placeholder="Status"
                      allowClear
                      style={{ width: 130 }}
                      value={statusFilter}
                      onChange={(val) => { setStatusFilter(val); setPage(1); }}
                      options={[
                        { label: 'Pending', value: 'pending' },
                        { label: 'Flagged', value: 'flagged' },
                        { label: 'Safe', value: 'safe' },
                        { label: 'Hidden', value: 'hidden' },
                      ]}
                    />
                    <Input
                      placeholder="Search content..."
                      prefix={<SearchOutlined />}
                      style={{ width: 200 }}
                      value={searchText}
                      onChange={(e) => setSearchText(e.target.value)}
                      onPressEnter={() => { setPage(1); fetchComments(); }}
                      allowClear
                    />
                    <RangePicker
                      value={dateRange as any}
                      onChange={(dates) => { setDateRange(dates as any); setPage(1); }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => { fetchComments(); fetchStats(); }}>
                      Refresh
                    </Button>
                  </Space>
                </Card>

                {/* Comments Table */}
                <Table
                  rowKey="id"
                  columns={columns}
                  dataSource={comments}
                  loading={loading}
                  pagination={{
                    current: page,
                    pageSize,
                    total,
                    onChange: (p) => setPage(p),
                    showSizeChanger: false,
                    showTotal: (t) => `${t} comments`,
                  }}
                  size="small"
                  scroll={{ x: 1000 }}
                />
              </>
            ),
          },
          {
            key: 'word-filter',
            label: 'Word Filter',
            children: (
              <>
                {/* Add Word Form */}
                <Card size="small" style={{ marginBottom: 16 }}>
                  <Form layout="inline">
                    <Form.Item>
                      <Input
                        placeholder="Enter word or phrase..."
                        value={newWord}
                        onChange={(e) => setNewWord(e.target.value)}
                        onPressEnter={handleAddWord}
                        style={{ width: 200 }}
                      />
                    </Form.Item>
                    <Form.Item>
                      <Select
                        value={newWordLevel}
                        onChange={setNewWordLevel}
                        style={{ width: 130 }}
                        options={[
                          { label: 'High (Block)', value: 'high' },
                          { label: 'Medium (Hide)', value: 'medium' },
                          { label: 'Low (Flag)', value: 'low' },
                        ]}
                      />
                    </Form.Item>
                    <Form.Item>
                      <Button type="primary" icon={<PlusOutlined />} onClick={handleAddWord}>
                        Add Word
                      </Button>
                    </Form.Item>
                  </Form>
                  <div style={{ marginTop: 8 }}>
                    <Text type="secondary">
                      <strong>High</strong>: blocks submission entirely &middot;{' '}
                      <strong>Medium</strong>: saved but auto-hidden for review &middot;{' '}
                      <strong>Low</strong>: visible but flagged for review
                    </Text>
                  </div>
                </Card>

                <Table
                  rowKey="id"
                  columns={wordFilterColumns}
                  dataSource={wordFilters}
                  loading={wordFiltersLoading}
                  pagination={false}
                  size="small"
                />
              </>
            ),
            destroyInactiveTabPane: false,
          },
        ]}
        onChange={(key) => {
          if (key === 'word-filter') fetchWordFilters();
        }}
      />

      {/* Detail Drawer */}
      <Drawer
        title="Comment Details"
        open={!!selectedComment}
        onClose={() => setSelectedComment(null)}
        width={isMobile ? '100%' : 480}
      >
        {selectedComment && (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <Descriptions column={1} size="small" bordered>
              <Descriptions.Item label="ID">{selectedComment.id}</Descriptions.Item>
              <Descriptions.Item label="Video">{selectedComment.videoTitle} (#{selectedComment.mediaId})</Descriptions.Item>
              <Descriptions.Item label="User">{selectedComment.user?.name || 'Anonymous'}</Descriptions.Item>
              <Descriptions.Item label="Date">{dayjs(selectedComment.createdAt).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
              <Descriptions.Item label="Status">{renderStatusTag(selectedComment)}</Descriptions.Item>
              {selectedComment.isHidden && (
                <>
                  <Descriptions.Item label="Hidden At">{selectedComment.hiddenAt ? dayjs(selectedComment.hiddenAt).format('YYYY-MM-DD HH:mm') : '-'}</Descriptions.Item>
                  <Descriptions.Item label="Hidden Reason"><Tag>{selectedComment.hiddenReason || 'manual'}</Tag></Descriptions.Item>
                </>
              )}
            </Descriptions>

            <div>
              <Text strong>Content</Text>
              <Paragraph style={{ whiteSpace: 'pre-wrap', padding: 12, borderRadius: 6, background: 'rgba(255,255,255,0.04)', marginTop: 8 }}>
                {selectedComment.content}
              </Paragraph>
            </div>

            {selectedComment.safetyReasoning && (
              <div>
                <Text strong>Safety Reasoning</Text>
                <Paragraph type="warning" style={{ marginTop: 4 }}>{selectedComment.safetyReasoning}</Paragraph>
              </div>
            )}

            {selectedComment.moderation && (
              <div>
                <Text strong>Moderation History</Text>
                <Descriptions column={1} size="small" style={{ marginTop: 8 }}>
                  <Descriptions.Item label="Decision"><Tag>{selectedComment.moderation.status}</Tag></Descriptions.Item>
                  <Descriptions.Item label="By">{selectedComment.moderation.moderator?.name || '-'}</Descriptions.Item>
                  <Descriptions.Item label="At">{selectedComment.moderation.moderatedAt ? dayjs(selectedComment.moderation.moderatedAt).format('YYYY-MM-DD HH:mm') : '-'}</Descriptions.Item>
                  {selectedComment.moderation.reason && (
                    <Descriptions.Item label="Reason">{selectedComment.moderation.reason}</Descriptions.Item>
                  )}
                </Descriptions>
              </div>
            )}

            <div>
              <Text strong>Moderation Notes</Text>
              <Input.TextArea
                value={notesInput}
                onChange={(e) => setNotesInput(e.target.value)}
                rows={3}
                placeholder="Add notes about this comment..."
                style={{ marginTop: 8 }}
              />
              <Button type="primary" size="small" onClick={handleSaveNotes} loading={savingNotes} style={{ marginTop: 8 }}>
                Save Notes
              </Button>
            </div>

            <Space>
              {selectedComment.safetyStatus !== 'safe' && !selectedComment.isHidden && (
                <Button type="primary" icon={<CheckCircleOutlined />} onClick={() => { handleApprove(selectedComment.id); setSelectedComment(null); }}>
                  Approve
                </Button>
              )}
              {!selectedComment.isHidden ? (
                <Button danger icon={<EyeInvisibleOutlined />} onClick={() => { handleHide(selectedComment.id); setSelectedComment(null); }}>
                  Hide
                </Button>
              ) : (
                <Button icon={<EyeOutlined />} onClick={() => { handleUnhide(selectedComment.id); setSelectedComment(null); }}>
                  Unhide
                </Button>
              )}
              <Popconfirm title="Permanently delete?" onConfirm={() => handleDelete(selectedComment.id)}>
                <Button danger icon={<DeleteOutlined />}>Delete</Button>
              </Popconfirm>
            </Space>
          </Space>
        )}
      </Drawer>
    </div>
  );
}
