import { useState, useEffect, useCallback } from 'react';
import {
  Table, Button, Space, Tag, Input, Select, Drawer, Form, Switch, Grid,
  DatePicker, InputNumber, Radio, Typography, Popconfirm, Divider,
  Descriptions, List, Card, Tooltip, App,
} from 'antd';
import {
  PlusOutlined, ReloadOutlined, CopyOutlined, PlayCircleOutlined,
  PauseCircleOutlined, UndoOutlined, InboxOutlined, DeleteOutlined,
  LinkOutlined, MinusCircleOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import PollResults from '@/components/polls/PollResults';
import type {
  StrawPoll, StrawPollType, StrawPollStatus, StrawPollIdentityMode,
} from '@/types/api';
import {
  STRAW_POLL_STATUS_COLORS, STRAW_POLL_STATUS_LABELS,
  STRAW_POLL_TYPE_LABELS, STRAW_POLL_IDENTITY_LABELS,
  STRAW_POLL_VISIBILITY_LABELS,
} from '@/types/api';

const { Search } = Input;
const { Text, Title } = Typography;

export default function StrawPollsPage() {
  const { message: msg } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [polls, setPolls] = useState<StrawPoll[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<StrawPollStatus | undefined>();

  // Drawers
  const [createOpen, setCreateOpen] = useState(false);
  const [detailOpen, setDetailOpen] = useState(false);
  const [selectedPoll, setSelectedPoll] = useState<StrawPoll | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const [createForm] = Form.useForm();
  const [pollType, setPollType] = useState<StrawPollType>('SINGLE_CHOICE');

  const fetchPolls = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, any> = { page, limit: 20 };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get('/straw-polls', { params });
      setPolls(data.polls);
      setTotal(data.total);
    } catch {
      msg.error('Failed to load polls');
    } finally {
      setLoading(false);
    }
  }, [page, search, statusFilter]);

  useEffect(() => { fetchPolls(); }, [fetchPolls]);

  const fetchDetail = async (id: string) => {
    setDetailLoading(true);
    try {
      const { data } = await api.get(`/straw-polls/${id}`);
      setSelectedPoll(data);
      setDetailOpen(true);
    } catch {
      msg.error('Failed to load poll details');
    } finally {
      setDetailLoading(false);
    }
  };

  const handleCreate = async (values: any) => {
    try {
      const payload = {
        ...values,
        closesAt: values.closesAt ? values.closesAt.toISOString() : undefined,
        options: values.type === 'YES_NO_ABSTAIN' ? undefined : values.options,
      };
      await api.post('/straw-polls', payload);
      msg.success('Poll created');
      setCreateOpen(false);
      createForm.resetFields();
      fetchPolls();
    } catch {
      msg.error('Failed to create poll');
    }
  };

  const handleLifecycle = async (id: string, action: string) => {
    try {
      await api.post(`/straw-polls/${id}/${action}`);
      msg.success(`Poll ${action}d`);
      fetchPolls();
      if (selectedPoll?.id === id) fetchDetail(id);
    } catch (err: any) {
      msg.error(err.response?.data?.error || `Failed to ${action} poll`);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/straw-polls/${id}`);
      msg.success('Poll deleted');
      fetchPolls();
      if (selectedPoll?.id === id) setDetailOpen(false);
    } catch {
      msg.error('Failed to delete poll');
    }
  };

  const copyLink = (slug: string) => {
    const url = `${window.location.origin}/straw-poll/${slug}`;
    navigator.clipboard.writeText(url);
    msg.success('Link copied');
  };

  const columns = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: StrawPoll) => (
        <a onClick={() => fetchDetail(record.id)}>{title}</a>
      ),
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 150,
      render: (type: StrawPollType) => <Tag>{STRAW_POLL_TYPE_LABELS[type]}</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: StrawPollStatus) => (
        <Tag color={STRAW_POLL_STATUS_COLORS[status]}>{STRAW_POLL_STATUS_LABELS[status]}</Tag>
      ),
    },
    {
      title: 'Identity',
      dataIndex: 'identityMode',
      key: 'identityMode',
      width: 130,
      render: (mode: StrawPollIdentityMode) => STRAW_POLL_IDENTITY_LABELS[mode],
    },
    {
      title: 'Votes',
      key: 'votes',
      width: 80,
      render: (_: any, record: StrawPoll) => record._count?.votes ?? 0,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 200,
      render: (_: any, record: StrawPoll) => (
        <Space size="small">
          <Tooltip title="Copy public link">
            <Button size="small" icon={<CopyOutlined />} onClick={() => copyLink(record.slug)} />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Button size="small" type="primary" icon={<PlayCircleOutlined />} onClick={() => handleLifecycle(record.id, 'activate')}>
              Activate
            </Button>
          )}
          {record.status === 'ACTIVE' && (
            <Button size="small" icon={<PauseCircleOutlined />} onClick={() => handleLifecycle(record.id, 'close')}>
              Close
            </Button>
          )}
          {record.status === 'CLOSED' && (
            <Space size="small">
              <Button size="small" icon={<UndoOutlined />} onClick={() => handleLifecycle(record.id, 'reopen')}>Reopen</Button>
              <Button size="small" icon={<InboxOutlined />} onClick={() => handleLifecycle(record.id, 'archive')}>Archive</Button>
            </Space>
          )}
          <Popconfirm title="Delete this poll?" onConfirm={() => handleDelete(record.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const drawerOpen = createOpen || detailOpen;
  const drawerWidth = isMobile ? 0 : (detailOpen ? 600 : 520);

  return (
    <>
      <div style={{ padding: 24, marginRight: drawerOpen ? drawerWidth : 0, transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)' }}>
        <Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 16 }}>
          <Title level={4} style={{ margin: 0 }}>Straw Polls</Title>
          <Space>
            <Search placeholder="Search polls..." allowClear onSearch={setSearch} style={{ width: 250 }} />
            <Select
              placeholder="Status"
              allowClear
              style={{ width: 130 }}
              onChange={setStatusFilter}
              options={Object.entries(STRAW_POLL_STATUS_LABELS).map(([k, v]) => ({ label: v, value: k }))}
            />
            <Button icon={<ReloadOutlined />} onClick={fetchPolls} />
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { createForm.resetFields(); setPollType('SINGLE_CHOICE'); setCreateOpen(true); }}>
              New Poll
            </Button>
          </Space>
        </Space>

        <Table
          dataSource={polls}
          columns={columns}
          scroll={{ x: 'max-content' }}
          rowKey="id"
          loading={loading}
          pagination={{ current: page, total, pageSize: 20, onChange: setPage, showSizeChanger: false }}
        />
      </div>

      {/* Create Drawer */}
      <Drawer
        title="Create Straw Poll"
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        width={isMobile ? '100%' : 520}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={<Button type="primary" onClick={() => createForm.submit()}>Create</Button>}
      >
        <Form form={createForm} layout="vertical" onFinish={handleCreate} initialValues={{ type: 'SINGLE_CHOICE', identityMode: 'ANONYMOUS', resultVisibility: 'LIVE', allowComments: true, isPrivate: false }}>
          <Form.Item name="title" label="Title" rules={[{ required: true, max: 200 }]}>
            <Input placeholder="e.g., Should we add bike lanes on Main Street?" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} maxLength={2000} />
          </Form.Item>
          <Form.Item name="type" label="Poll Type" rules={[{ required: true }]}>
            <Radio.Group onChange={(e) => setPollType(e.target.value)}>
              <Radio.Button value="SINGLE_CHOICE">Single Choice</Radio.Button>
              <Radio.Button value="YES_NO_ABSTAIN">Yes / No / Abstain</Radio.Button>
            </Radio.Group>
          </Form.Item>

          {pollType === 'SINGLE_CHOICE' && (
            <Form.List name="options" initialValue={[{ label: '' }, { label: '' }]}>
              {(fields, { add, remove }) => (
                <div>
                  <Text strong>Options</Text>
                  {fields.map((field, index) => (
                    <Space key={field.key} style={{ display: 'flex', marginBottom: 8, marginTop: index === 0 ? 8 : 0 }} align="baseline">
                      <Form.Item {...field} name={[field.name, 'label']} rules={[{ required: true, message: 'Option required' }]} style={{ marginBottom: 0, flex: 1 }}>
                        <Input placeholder={`Option ${index + 1}`} />
                      </Form.Item>
                      {fields.length > 2 && (
                        <MinusCircleOutlined onClick={() => remove(field.name)} style={{ color: '#ff4d4f' }} />
                      )}
                    </Space>
                  ))}
                  {fields.length < 20 && (
                    <Button type="dashed" onClick={() => add({ label: '' })} icon={<PlusOutlined />} style={{ width: '100%', marginTop: 8 }}>
                      Add Option
                    </Button>
                  )}
                </div>
              )}
            </Form.List>
          )}

          <Divider />

          <Form.Item name="identityMode" label="Identity Mode">
            <Select options={Object.entries(STRAW_POLL_IDENTITY_LABELS).map(([k, v]) => ({ label: v, value: k }))} />
          </Form.Item>
          <Form.Item name="resultVisibility" label="Result Visibility">
            <Select options={Object.entries(STRAW_POLL_VISIBILITY_LABELS).map(([k, v]) => ({ label: v, value: k }))} />
          </Form.Item>
          <Form.Item name="closesAt" label="Auto-close Date">
            <DatePicker showTime format="YYYY-MM-DD HH:mm" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="closeThreshold" label="Auto-close Vote Threshold">
            <InputNumber min={1} max={100000} style={{ width: '100%' }} placeholder="Close after N votes" />
          </Form.Item>
          <Space>
            <Form.Item name="allowComments" valuePropName="checked"><Switch checkedChildren="Comments" unCheckedChildren="No Comments" /></Form.Item>
            <Form.Item name="isPrivate" valuePropName="checked"><Switch checkedChildren="Private" unCheckedChildren="Public" /></Form.Item>
          </Space>
        </Form>
      </Drawer>

      {/* Detail Drawer */}
      <Drawer
        title={selectedPoll?.title || 'Poll Detail'}
        open={detailOpen}
        onClose={() => setDetailOpen(false)}
        width={isMobile ? '100%' : 600}
        loading={detailLoading}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      >
        {selectedPoll && (
          <div>
            <Descriptions column={2} size="small" bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="Status">
                <Tag color={STRAW_POLL_STATUS_COLORS[selectedPoll.status]}>{STRAW_POLL_STATUS_LABELS[selectedPoll.status]}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Type">{STRAW_POLL_TYPE_LABELS[selectedPoll.type]}</Descriptions.Item>
              <Descriptions.Item label="Identity">{STRAW_POLL_IDENTITY_LABELS[selectedPoll.identityMode]}</Descriptions.Item>
              <Descriptions.Item label="Visibility">{STRAW_POLL_VISIBILITY_LABELS[selectedPoll.resultVisibility]}</Descriptions.Item>
              <Descriptions.Item label="Created">{dayjs(selectedPoll.createdAt).format('MMM D, YYYY h:mm A')}</Descriptions.Item>
              <Descriptions.Item label="Closes">{selectedPoll.closesAt ? dayjs(selectedPoll.closesAt).format('MMM D, YYYY h:mm A') : 'Manual'}</Descriptions.Item>
            </Descriptions>

            {selectedPoll.description && (
              <Card size="small" style={{ marginBottom: 16 }}>
                <Text>{selectedPoll.description}</Text>
              </Card>
            )}

            {/* Lifecycle Controls */}
            <Space style={{ marginBottom: 16 }}>
              {selectedPoll.status === 'DRAFT' && (
                <Button type="primary" icon={<PlayCircleOutlined />} onClick={() => handleLifecycle(selectedPoll.id, 'activate')}>Activate</Button>
              )}
              {selectedPoll.status === 'ACTIVE' && (
                <Button icon={<PauseCircleOutlined />} onClick={() => handleLifecycle(selectedPoll.id, 'close')}>Close</Button>
              )}
              {selectedPoll.status === 'CLOSED' && (
                <>
                  <Button icon={<UndoOutlined />} onClick={() => handleLifecycle(selectedPoll.id, 'reopen')}>Reopen</Button>
                  <Button icon={<InboxOutlined />} onClick={() => handleLifecycle(selectedPoll.id, 'archive')}>Archive</Button>
                </>
              )}
              <Button icon={<LinkOutlined />} onClick={() => copyLink(selectedPoll.slug)}>Copy Link</Button>
            </Space>

            {/* Results */}
            <Divider>Vote Results</Divider>
            {selectedPoll.options && (
              <PollResults
                options={selectedPoll.options}
                totalVotes={selectedPoll._count?.votes ?? 0}
                type={selectedPoll.type}
              />
            )}

            {/* Voters */}
            {selectedPoll.votes && selectedPoll.votes.length > 0 && (
              <>
                <Divider>Voters ({selectedPoll.votes.length})</Divider>
                <List
                  size="small"
                  dataSource={selectedPoll.votes}
                  renderItem={(vote: any) => (
                    <List.Item
                      extra={
                        <Popconfirm title="Remove this vote?" onConfirm={() => api.delete(`/straw-polls/${selectedPoll.id}/votes/${vote.id}`).then(() => fetchDetail(selectedPoll.id))}>
                          <Button size="small" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                      }
                    >
                      <List.Item.Meta
                        title={vote.user?.name || vote.voterName || 'Anonymous'}
                        description={`Voted for: ${selectedPoll.options?.find(o => o.id === vote.optionId)?.label || 'Unknown'} — ${dayjs(vote.createdAt).format('MMM D, h:mm A')}`}
                      />
                    </List.Item>
                  )}
                />
              </>
            )}

            {/* Comments */}
            {selectedPoll.comments && selectedPoll.comments.length > 0 && (
              <>
                <Divider>Comments ({selectedPoll.comments.length})</Divider>
                <List
                  size="small"
                  dataSource={selectedPoll.comments}
                  renderItem={(comment: any) => (
                    <List.Item
                      extra={
                        <Popconfirm title="Delete comment?" onConfirm={() => api.delete(`/straw-polls/${selectedPoll.id}/comments/${comment.id}`).then(() => fetchDetail(selectedPoll.id))}>
                          <Button size="small" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                      }
                    >
                      <List.Item.Meta title={comment.authorName} description={comment.content} />
                      <Text type="secondary" style={{ fontSize: 12 }}>{dayjs(comment.createdAt).format('MMM D, h:mm A')}</Text>
                    </List.Item>
                  )}
                />
              </>
            )}
          </div>
        )}
      </Drawer>
    </>
  );
}
