import { useState, useEffect, useCallback } from 'react';
import {
  Row, Col, Card, Statistic, Table, Button, App, Tag, Space, Tabs, Popconfirm,
  Form, Input, Switch, Alert, Divider,
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  MessageOutlined,
  FileTextOutlined,
  ReloadOutlined,
  SettingOutlined,
  SaveOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import { useSettingsStore } from '@/stores/settings.store';
import { useMobile } from '@/hooks/useMobile';
import type { AppOutletContext } from '@/types/api';

interface DocsCommentItem {
  id: string;
  pagePath: string;
  authorName: string;
  authorEmail?: string;
  body: string;
  status: 'PENDING' | 'APPROVED' | 'REJECTED';
  reviewedAt?: string;
  reviewedBy?: string;
  createdAt: string;
}

interface ModerationResponse {
  items: DocsCommentItem[];
  total: number;
  page: number;
  pageSize: number;
}

interface CommentStats {
  pending: number;
  approved: number;
  rejected: number;
  totalPages: number;
}

const STATUS_COLORS: Record<string, string> = {
  PENDING: 'orange',
  APPROVED: 'green',
  REJECTED: 'red',
};

// --- Settings Tab ---

function SettingsTab() {
  const { message } = App.useApp();
  const { fetchAdminSettings } = useSettingsStore();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [setupLoading, setSetupLoading] = useState(false);
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    api.get('/settings/admin')
      .then(({ data }) => {
        form.setFieldsValue({
          enableDocsComments: data.enableDocsComments ?? false,
          giteaApiToken: data.giteaApiToken ?? '',
          giteaCommentsRepoOwner: data.giteaCommentsRepoOwner ?? '',
          giteaCommentsRepoName: data.giteaCommentsRepoName || 'docs-comments',
          giteaOauthClientId: data.giteaOauthClientId ?? '',
          giteaOauthClientSecret: data.giteaOauthClientSecret ?? '',
        });
        setEnabled(data.enableDocsComments ?? false);
      })
      .catch(() => message.error('Failed to load settings'))
      .finally(() => setLoading(false));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const handleSave = async () => {
    setSaving(true);
    try {
      const values = await form.validateFields();
      await api.put('/settings', values);
      message.success('Docs comments settings saved');
      fetchAdminSettings();
    } catch {
      message.error('Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const handleSetup = async () => {
    setSetupLoading(true);
    try {
      // Save settings first so the API can read them
      const values = await form.validateFields();
      await api.put('/settings', values);

      const { data } = await api.post('/docs-comments/setup');
      message.success(`Gitea repo "${data.repo}" ready with labels: ${data.labels.join(', ')}`);
      fetchAdminSettings();
    } catch {
      message.error('Setup failed. Make sure comments are enabled and the API token + repo owner are set.');
    } finally {
      setSetupLoading(false);
    }
  };

  if (loading) return null;

  return (
    <Card size="small">
      <Alert
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
        message="Gitea-backed comments for documentation pages"
        description="Comments are stored as Gitea issues. Anonymous comments go through a moderation queue. Authenticated users comment via Gitea OAuth2 login."
      />

      <Form form={form} layout="vertical" style={{ maxWidth: 600, width: '100%' }}>
        <Form.Item name="enableDocsComments" label="Enable Docs Comments" valuePropName="checked">
          <Switch onChange={(val) => setEnabled(val)} />
        </Form.Item>

        {enabled && (
          <>
            <Divider orientation="left" plain>Gitea Connection</Divider>

            <Form.Item
              name="giteaApiToken"
              label="API Token"
              extra="Personal Access Token with repo write scope. Create in Gitea > Settings > Applications."
              rules={[{ required: true, message: 'API token is required' }]}
            >
              <Input.Password placeholder="Gitea Personal Access Token" />
            </Form.Item>

            <Form.Item
              name="giteaCommentsRepoOwner"
              label="Repository Owner"
              extra="Gitea username that will own the docs-comments repository."
              rules={[{ required: true, message: 'Repo owner is required' }]}
            >
              <Input placeholder="e.g. admin" />
            </Form.Item>

            <Form.Item
              name="giteaCommentsRepoName"
              label="Repository Name"
              extra="Will be auto-created when you run Setup."
            >
              <Input placeholder="docs-comments" />
            </Form.Item>

            <Divider orientation="left" plain>OAuth2 Login (Optional)</Divider>

            <Alert
              type="warning"
              showIcon
              style={{ marginBottom: 16 }}
              message="Optional — enables 'Sign in with Gitea' on docs pages"
              description={
                <>
                  Create an OAuth2 Application in Gitea &gt; Settings &gt; Applications. Set redirect URIs to:
                  <br /><code>https://{'<your-domain>'}/comments/callback/</code>
                  <br /><code>http://localhost:4003/comments/callback/</code>
                </>
              }
            />

            <Form.Item name="giteaOauthClientId" label="OAuth Client ID">
              <Input placeholder="OAuth2 Application Client ID" />
            </Form.Item>

            <Form.Item name="giteaOauthClientSecret" label="OAuth Client Secret">
              <Input.Password placeholder="OAuth2 Application Client Secret" />
            </Form.Item>
          </>
        )}

        <Divider />

        <Space>
          <Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
            Save Settings
          </Button>
          {enabled && (
            <Popconfirm
              title="Setup Gitea Comments?"
              description="This will save settings, then create the docs-comments repository and labels in Gitea."
              onConfirm={handleSetup}
            >
              <Button icon={<ThunderboltOutlined />} loading={setupLoading}>
                Save &amp; Setup Repo
              </Button>
            </Popconfirm>
          )}
        </Space>
      </Form>
    </Card>
  );
}

// --- Main Page ---

export default function DocsCommentsPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();
  const { isMobile } = useMobile();
  const [activeTab, setActiveTab] = useState('moderation');
  const [stats, setStats] = useState<CommentStats | null>(null);
  const [comments, setComments] = useState<DocsCommentItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [statusFilter, setStatusFilter] = useState<string | undefined>('PENDING');
  const [loading, setLoading] = useState(false);
  const [moderating, setModerating] = useState<Record<string, boolean>>({});

  const fetchStats = useCallback(() => {
    api.get('/docs-comments/stats').then(({ data }) => setStats(data)).catch(() => {});
  }, []);

  const fetchComments = useCallback(() => {
    setLoading(true);
    const params: Record<string, string | number> = { page, pageSize };
    if (statusFilter) params.status = statusFilter;

    api
      .get('/docs-comments/moderation', { params })
      .then(({ data }: { data: ModerationResponse }) => {
        setComments(data.items);
        setTotal(data.total);
      })
      .catch(() => message.error('Failed to load comments'))
      .finally(() => setLoading(false));
  }, [page, pageSize, statusFilter, message]);

  useEffect(() => {
    setPageHeader({ title: 'Docs Comments' });
    fetchStats();
    return () => setPageHeader(null);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (activeTab === 'moderation') fetchComments();
  }, [fetchComments, activeTab]);

  const handleModerate = async (id: string, action: 'approve' | 'reject') => {
    setModerating((prev) => ({ ...prev, [id]: true }));
    try {
      await api.post(`/docs-comments/moderation/${id}`, { action });
      message.success(`Comment ${action}d`);
      fetchComments();
      fetchStats();
    } catch {
      message.error(`Failed to ${action} comment`);
    } finally {
      setModerating((prev) => ({ ...prev, [id]: false }));
    }
  };

  const columns = [
    {
      title: 'Page',
      dataIndex: 'pagePath',
      key: 'pagePath',
      ellipsis: true,
      width: 200,
      render: (path: string) => (
        <span style={{ fontFamily: 'monospace', fontSize: 12 }} title={path}>
          {path}
        </span>
      ),
    },
    {
      title: 'Author',
      dataIndex: 'authorName',
      key: 'authorName',
      width: 140,
      responsive: ['md'] as any,
      render: (name: string, record: DocsCommentItem) => (
        <span title={record.authorEmail || undefined}>{name}</span>
      ),
    },
    {
      title: 'Comment',
      dataIndex: 'body',
      key: 'body',
      ellipsis: true,
      render: (body: string) => (
        <span style={{ fontSize: 13 }}>{body.slice(0, 200)}{body.length > 200 ? '...' : ''}</span>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={STATUS_COLORS[status]}>{status}</Tag>
      ),
    },
    {
      title: 'Date',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 140,
      responsive: ['md'] as any,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 180,
      render: (_: unknown, record: DocsCommentItem) => {
        if (record.status !== 'PENDING') {
          return <Tag>{record.status === 'APPROVED' ? 'Approved' : 'Rejected'}</Tag>;
        }
        return (
          <Space size="small">
            <Button
              type="primary"
              size="small"
              icon={<CheckCircleOutlined />}
              loading={moderating[record.id]}
              onClick={() => handleModerate(record.id, 'approve')}
            >
              {!isMobile && 'Approve'}
            </Button>
            <Popconfirm
              title="Reject this comment?"
              description="The comment will be removed from Gitea."
              onConfirm={() => handleModerate(record.id, 'reject')}
            >
              <Button
                danger
                size="small"
                icon={<CloseCircleOutlined />}
                loading={moderating[record.id]}
              >
                {!isMobile && 'Reject'}
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const moderationContent = (
    <>
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Pending"
              value={stats?.pending ?? 0}
              prefix={<ClockCircleOutlined />}
              valueStyle={stats?.pending ? { color: '#faad14' } : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="Approved" value={stats?.approved ?? 0} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="Rejected" value={stats?.rejected ?? 0} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="Pages" value={stats?.totalPages ?? 0} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
      </Row>

      <Card
        size="small"
        extra={
          <Button size="small" icon={<ReloadOutlined />} onClick={() => { fetchComments(); fetchStats(); }}>
            Refresh
          </Button>
        }
      >
        <Tabs
          activeKey={statusFilter || 'ALL'}
          onChange={(key) => {
            setStatusFilter(key === 'ALL' ? undefined : key);
            setPage(1);
          }}
          items={[
            { key: 'PENDING', label: <><ClockCircleOutlined /> Pending{stats?.pending ? ` (${stats.pending})` : ''}</> },
            { key: 'APPROVED', label: <><CheckCircleOutlined /> Approved</> },
            { key: 'REJECTED', label: <><CloseCircleOutlined /> Rejected</> },
            { key: 'ALL', label: <><MessageOutlined /> All</> },
          ]}
        />
        <Table
          dataSource={comments}
          columns={columns}
          scroll={{ x: 'max-content' }}
          rowKey="id"
          loading={loading}
          size="small"
          pagination={{
            current: page,
            pageSize,
            total,
            onChange: (p) => setPage(p),
            showSizeChanger: false,
            showTotal: (t) => `${t} comments`,
          }}
        />
      </Card>
    </>
  );

  return (
    <Tabs
      activeKey={activeTab}
      onChange={setActiveTab}
      items={[
        {
          key: 'moderation',
          label: <><MessageOutlined /> Moderation{stats?.pending ? ` (${stats.pending})` : ''}</>,
          children: moderationContent,
        },
        {
          key: 'settings',
          label: <><SettingOutlined /> Settings</>,
          children: <SettingsTab />,
        },
      ]}
    />
  );
}
