import { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Tag,
  Space,
  Form,
  Popconfirm,
  message,
  Typography,
  Row,
  Col,
  Drawer,
  Card,
  Grid,
  InputNumber,
  Switch,
  List,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
  FileTextOutlined,
  EditOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type {
  MeetingAgenda,
  ActionItem,
  AgendasListResponse,
  AgendaStatus,
  ActionItemStatus,
  AgendaItem,
} from '@/types/api';
import {
  ACTION_ITEM_STATUS_COLORS,
  ACTION_ITEM_STATUS_LABELS,
  ACTION_ITEM_PRIORITY_COLORS,
} from '@/types/api';

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

const AGENDA_STATUS_COLORS: Record<AgendaStatus, string> = {
  draft: 'default',
  active: 'blue',
  completed: 'green',
};

const AGENDA_STATUS_LABELS: Record<AgendaStatus, string> = {
  draft: 'Draft',
  active: 'Active',
  completed: 'Completed',
};

export default function MeetingAgendaPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  // Main table state
  const [agendas, setAgendas] = useState<MeetingAgenda[]>([]);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<AgendaStatus | undefined>();

  // Create drawer
  const [createOpen, setCreateOpen] = useState(false);
  const [createForm] = Form.useForm();
  const [creating, setCreating] = useState(false);

  // Detail drawer
  const [detailOpen, setDetailOpen] = useState(false);
  const [selectedAgenda, setSelectedAgenda] = useState<MeetingAgenda | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  // Minutes editing state
  const [minutesNotes, setMinutesNotes] = useState('');
  const [minutesDecisions, setMinutesDecisions] = useState<Array<{ id: string; text: string; passed: boolean }>>([]);
  const [minutesAttendees, setMinutesAttendees] = useState<Array<{ name: string; pronouns?: string; userId?: string }>>([]);
  const [savingMinutes, setSavingMinutes] = useState(false);
  const [approvingMinutes, setApprovingMinutes] = useState(false);

  // Agenda items editing in detail drawer
  const [editingItems, setEditingItems] = useState<AgendaItem[]>([]);
  const [savingItems, setSavingItems] = useState(false);

  // New decision / attendee inputs
  const [newDecisionText, setNewDecisionText] = useState('');
  const [newAttendeeName, setNewAttendeeName] = useState('');

  // Polls and shifts for selects
  const [pollOptions, setPollOptions] = useState<Array<{ value: string; label: string }>>([]);
  const [shiftOptions, setShiftOptions] = useState<Array<{ value: string; label: string }>>([]);

  const fetchAgendas = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, any> = { page: pagination.page, limit: pagination.limit };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get<AgendasListResponse>('/meetings/agendas', { params });
      setAgendas(data.agendas);
      setPagination((p) => ({ ...p, total: data.pagination.total }));
    } catch {
      message.error('Failed to load agendas');
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.limit, search, statusFilter]);

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

  // Fetch poll/shift options when create drawer opens
  useEffect(() => {
    if (!createOpen) return;
    const fetchOptions = async () => {
      try {
        const [pollsRes, shiftsRes] = await Promise.all([
          api.get('/meeting-planner', { params: { limit: 100 } }).catch(() => ({ data: { polls: [] } })),
          api.get('/map/shifts', { params: { limit: 100 } }).catch(() => ({ data: { shifts: [] } })),
        ]);
        setPollOptions(
          (pollsRes.data.polls || []).map((p: any) => ({ value: p.id, label: p.title }))
        );
        setShiftOptions(
          (shiftsRes.data.shifts || []).map((s: any) => ({
            value: s.id,
            label: `${s.title} - ${dayjs(s.date).format('MMM D')}`,
          }))
        );
      } catch {
        // Silent — selects will just be empty
      }
    };
    fetchOptions();
  }, [createOpen]);

  const fetchAgendaDetail = async (id: string) => {
    setDetailLoading(true);
    try {
      const { data } = await api.get<MeetingAgenda>(`/meetings/agendas/${id}`);
      setSelectedAgenda(data);
      setEditingItems(data.items || []);
      // Populate minutes state
      if (data.minutes) {
        setMinutesNotes(data.minutes.notes || '');
        setMinutesDecisions(data.minutes.decisions || []);
        setMinutesAttendees(data.minutes.attendees || []);
      } else {
        setMinutesNotes('');
        setMinutesDecisions([]);
        setMinutesAttendees([]);
      }
      setDetailOpen(true);
    } catch {
      message.error('Failed to load agenda details');
    } finally {
      setDetailLoading(false);
    }
  };

  const handleCreate = async (values: any) => {
    setCreating(true);
    try {
      await api.post('/meetings/agendas', {
        title: values.title,
        pollId: values.pollId || null,
        shiftId: values.shiftId || null,
      });
      message.success('Agenda created');
      setCreateOpen(false);
      createForm.resetFields();
      fetchAgendas();
    } catch {
      message.error('Failed to create agenda');
    } finally {
      setCreating(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/meetings/agendas/${id}`);
      message.success('Agenda deleted');
      fetchAgendas();
    } catch {
      message.error('Failed to delete agenda');
    }
  };

  // Agenda items management
  const handleMoveItem = (index: number, direction: 'up' | 'down') => {
    const items = [...editingItems];
    const swapIndex = direction === 'up' ? index - 1 : index + 1;
    if (swapIndex < 0 || swapIndex >= items.length) return;
    [items[index], items[swapIndex]] = [items[swapIndex]!, items[index]!];
    // Recalculate order
    items.forEach((item, i) => { item.order = i; });
    setEditingItems(items);
  };

  const handleAddItem = () => {
    const newItem: AgendaItem = {
      id: `temp-${Date.now()}`,
      title: '',
      durationMinutes: 5,
      order: editingItems.length,
    };
    setEditingItems([...editingItems, newItem]);
  };

  const handleRemoveItem = (index: number) => {
    const items = editingItems.filter((_, i) => i !== index);
    items.forEach((item, i) => { item.order = i; });
    setEditingItems(items);
  };

  const handleUpdateItem = (index: number, field: keyof AgendaItem, value: any) => {
    const items = [...editingItems];
    (items[index] as any)[field] = value;
    setEditingItems(items);
  };

  const handleSaveItems = async () => {
    if (!selectedAgenda) return;
    setSavingItems(true);
    try {
      const items = editingItems.map((item, i) => ({
        id: item.id.startsWith('temp-') ? undefined : item.id,
        title: item.title,
        durationMinutes: item.durationMinutes,
        order: i,
      }));
      await api.put(`/meetings/agendas/${selectedAgenda.id}`, { items });
      message.success('Agenda items saved');
      fetchAgendaDetail(selectedAgenda.id);
      fetchAgendas();
    } catch {
      message.error('Failed to save agenda items');
    } finally {
      setSavingItems(false);
    }
  };

  // Minutes management
  const handleSaveMinutes = async () => {
    if (!selectedAgenda) return;
    setSavingMinutes(true);
    try {
      const payload = {
        notes: minutesNotes,
        decisions: minutesDecisions,
        attendees: minutesAttendees,
      };
      if (selectedAgenda.minutes) {
        await api.put(`/meetings/agendas/${selectedAgenda.id}/minutes`, payload);
      } else {
        await api.post(`/meetings/agendas/${selectedAgenda.id}/minutes`, payload);
      }
      message.success('Minutes saved');
      fetchAgendaDetail(selectedAgenda.id);
    } catch {
      message.error('Failed to save minutes');
    } finally {
      setSavingMinutes(false);
    }
  };

  const handleApproveMinutes = async () => {
    if (!selectedAgenda) return;
    setApprovingMinutes(true);
    try {
      await api.post(`/meetings/agendas/${selectedAgenda.id}/minutes/approve`);
      message.success('Minutes approved');
      fetchAgendaDetail(selectedAgenda.id);
    } catch {
      message.error('Failed to approve minutes');
    } finally {
      setApprovingMinutes(false);
    }
  };

  // Action item inline status change
  const handleActionItemStatusChange = async (actionItem: ActionItem, newStatus: ActionItemStatus) => {
    try {
      await api.put(`/meetings/agendas/${actionItem.agendaId}/action-items/${actionItem.id}`, {
        status: newStatus,
      });
      message.success('Action item updated');
      if (selectedAgenda) fetchAgendaDetail(selectedAgenda.id);
    } catch {
      message.error('Failed to update action item');
    }
  };

  // Add decision
  const handleAddDecision = () => {
    if (!newDecisionText.trim()) return;
    setMinutesDecisions([
      ...minutesDecisions,
      { id: `d-${Date.now()}`, text: newDecisionText.trim(), passed: false },
    ]);
    setNewDecisionText('');
  };

  const handleRemoveDecision = (index: number) => {
    setMinutesDecisions(minutesDecisions.filter((_, i) => i !== index));
  };

  const handleToggleDecisionPassed = (index: number) => {
    const decisions = [...minutesDecisions];
    decisions[index] = { ...decisions[index]!, passed: !decisions[index]!.passed };
    setMinutesDecisions(decisions);
  };

  // Add attendee
  const handleAddAttendee = () => {
    if (!newAttendeeName.trim()) return;
    setMinutesAttendees([...minutesAttendees, { name: newAttendeeName.trim() }]);
    setNewAttendeeName('');
  };

  const handleRemoveAttendee = (index: number) => {
    setMinutesAttendees(minutesAttendees.filter((_, i) => i !== index));
  };

  const getLinkedLabel = (record: MeetingAgenda) => {
    if (record.pollId) return <Tag color="purple">Poll</Tag>;
    if (record.shiftId) return <Tag color="cyan">Shift</Tag>;
    return <Text type="secondary">None</Text>;
  };

  const columns: ColumnsType<MeetingAgenda> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record) => (
        <Button type="link" onClick={() => fetchAgendaDetail(record.id)} style={{ padding: 0 }}>
          {title}
        </Button>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 110,
      render: (status: AgendaStatus) => (
        <Tag color={AGENDA_STATUS_COLORS[status]}>{AGENDA_STATUS_LABELS[status]}</Tag>
      ),
    },
    {
      title: 'Linked To',
      key: 'linked',
      width: 100,
      render: (_, record) => getLinkedLabel(record),
      responsive: ['md'],
    },
    {
      title: 'Items',
      key: 'items',
      width: 70,
      render: (_, record) => record.items?.length ?? 0,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => dayjs(date).format('MMM D, YYYY'),
      responsive: ['md'],
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_, record) => (
        <Space size="small">
          <Button size="small" icon={<EditOutlined />} onClick={() => fetchAgendaDetail(record.id)} />
          <Popconfirm title="Delete this agenda?" onConfirm={() => handleDelete(record.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const getActiveDrawerWidth = () => {
    if (createOpen) return 560;
    if (detailOpen) return 720;
    return 0;
  };
  const activeDrawerWidth = getActiveDrawerWidth();

  const actionItemColumns: ColumnsType<ActionItem> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: 'Assignee',
      key: 'assignee',
      width: 120,
      render: (_, record) => record.assignee?.name || record.assignee?.email || <Text type="secondary">Unassigned</Text>,
    },
    {
      title: 'Priority',
      dataIndex: 'priority',
      key: 'priority',
      width: 90,
      render: (priority) => (
        <Tag color={ACTION_ITEM_PRIORITY_COLORS[priority as keyof typeof ACTION_ITEM_PRIORITY_COLORS]}>
          {priority}
        </Tag>
      ),
    },
    {
      title: 'Due',
      dataIndex: 'dueDate',
      key: 'dueDate',
      width: 100,
      render: (date: string | null) => date ? dayjs(date).format('MMM D') : '-',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: ActionItemStatus, record) => (
        <Select
          size="small"
          value={status}
          style={{ width: '100%' }}
          onChange={(val) => handleActionItemStatusChange(record, val)}
          options={Object.entries(ACTION_ITEM_STATUS_LABELS).map(([value, label]) => ({
            value,
            label: <Tag color={ACTION_ITEM_STATUS_COLORS[value as ActionItemStatus]}>{label}</Tag>,
          }))}
        />
      ),
    },
  ];

  return (
    <div style={{ padding: screens.md ? 24 : 16 }}>
      <div
        style={{
          marginRight: isMobile ? 0 : activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
        <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
          <Col>
            <Title level={4} style={{ margin: 0 }}>
              <FileTextOutlined style={{ marginRight: 8 }} />
              Meeting Agendas
            </Title>
          </Col>
          <Col>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
              {screens.md ? 'Create Agenda' : 'New'}
            </Button>
          </Col>
        </Row>

        {/* Filters */}
        <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
          <Col xs={24} sm={12} md={8}>
            <Input
              placeholder="Search agendas..."
              prefix={<SearchOutlined />}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              allowClear
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="Filter by status"
              style={{ width: '100%' }}
              allowClear
              value={statusFilter}
              onChange={setStatusFilter}
              options={Object.entries(AGENDA_STATUS_LABELS).map(([value, label]) => ({ value, label }))}
            />
          </Col>
        </Row>

        <Table
          dataSource={agendas}
          columns={columns}
          scroll={{ x: 'max-content' }}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.page,
            pageSize: pagination.limit,
            total: pagination.total,
            showSizeChanger: false,
            onChange: (page) => setPagination((p) => ({ ...p, page })),
          }}
          size="small"
        />
      </div>

      {/* Create Agenda Drawer */}
      <Drawer
        title="Create Agenda"
        open={createOpen}
        onClose={() => { setCreateOpen(false); createForm.resetFields(); }}
        width={isMobile ? '100%' : 560}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={() => { setCreateOpen(false); createForm.resetFields(); }} disabled={creating}>
              Cancel
            </Button>
            <Button type="primary" loading={creating} onClick={() => createForm.submit()}>
              Create
            </Button>
          </Space>
        }
      >
        <Form form={createForm} layout="vertical" onFinish={handleCreate}>
          <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Title is required' }]}>
            <Input placeholder="e.g., Weekly Team Meeting" />
          </Form.Item>
          <Form.Item name="pollId" label="Link to Poll (optional)">
            <Select
              placeholder="Select a poll"
              allowClear
              showSearch
              optionFilterProp="label"
              options={pollOptions}
            />
          </Form.Item>
          <Form.Item name="shiftId" label="Link to Shift (optional)">
            <Select
              placeholder="Select a shift"
              allowClear
              showSearch
              optionFilterProp="label"
              options={shiftOptions}
            />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Detail Drawer */}
      <Drawer
        title={selectedAgenda?.title || 'Agenda Details'}
        open={detailOpen}
        onClose={() => { setDetailOpen(false); setSelectedAgenda(null); }}
        width={isMobile ? '100%' : 720}
        loading={detailLoading}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      >
        {selectedAgenda && (
          <>
            {/* Metadata */}
            <Row gutter={[16, 8]} style={{ marginBottom: 16 }}>
              <Col>
                <Tag color={AGENDA_STATUS_COLORS[selectedAgenda.status]}>
                  {AGENDA_STATUS_LABELS[selectedAgenda.status]}
                </Tag>
              </Col>
              <Col>{getLinkedLabel(selectedAgenda)}</Col>
              <Col>
                <Text type="secondary">
                  Created {dayjs(selectedAgenda.createdAt).format('MMM D, YYYY')}
                  {selectedAgenda.createdBy?.name ? ` by ${selectedAgenda.createdBy.name}` : ''}
                </Text>
              </Col>
            </Row>

            {/* Agenda Items */}
            <Card
              size="small"
              title="Agenda Items"
              style={{ marginBottom: 16 }}
              extra={
                <Space>
                  <Button size="small" icon={<PlusOutlined />} onClick={handleAddItem}>
                    Add
                  </Button>
                  <Button
                    size="small"
                    type="primary"
                    loading={savingItems}
                    onClick={handleSaveItems}
                    disabled={editingItems.length === 0}
                  >
                    Save Items
                  </Button>
                </Space>
              }
            >
              {editingItems.length === 0 ? (
                <Text type="secondary">No agenda items yet. Click Add to get started.</Text>
              ) : (
                editingItems.map((item, index) => (
                  <Row
                    key={item.id}
                    gutter={8}
                    align="middle"
                    style={{
                      marginBottom: 8,
                      padding: '8px 0',
                      borderBottom: index < editingItems.length - 1 ? '1px solid #f0f0f0' : undefined,
                    }}
                  >
                    <Col flex="none">
                      <Space direction="vertical" size={0}>
                        <Button
                          size="small"
                          type="text"
                          icon={<ArrowUpOutlined />}
                          disabled={index === 0}
                          onClick={() => handleMoveItem(index, 'up')}
                        />
                        <Button
                          size="small"
                          type="text"
                          icon={<ArrowDownOutlined />}
                          disabled={index === editingItems.length - 1}
                          onClick={() => handleMoveItem(index, 'down')}
                        />
                      </Space>
                    </Col>
                    <Col flex="auto">
                      <Input
                        placeholder="Item title"
                        value={item.title}
                        onChange={(e) => handleUpdateItem(index, 'title', e.target.value)}
                        size="small"
                      />
                    </Col>
                    <Col flex="none">
                      <InputNumber
                        min={1}
                        max={480}
                        value={item.durationMinutes}
                        onChange={(val) => handleUpdateItem(index, 'durationMinutes', val)}
                        size="small"
                        style={{ width: 70 }}
                        addonAfter="min"
                      />
                    </Col>
                    <Col flex="none">
                      <Button
                        size="small"
                        danger
                        type="text"
                        icon={<DeleteOutlined />}
                        onClick={() => handleRemoveItem(index)}
                      />
                    </Col>
                  </Row>
                ))
              )}
              {editingItems.length > 0 && (
                <Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
                  Total: {editingItems.reduce((sum, item) => sum + (item.durationMinutes || 0), 0)} min
                </Text>
              )}
            </Card>

            {/* Minutes Section */}
            <Card
              size="small"
              title="Minutes"
              style={{ marginBottom: 16 }}
              extra={
                <Space>
                  <Button size="small" type="primary" loading={savingMinutes} onClick={handleSaveMinutes}>
                    Save Minutes
                  </Button>
                  {selectedAgenda.minutes && !selectedAgenda.minutes.approvedAt && (
                    <Popconfirm title="Approve these minutes?" onConfirm={handleApproveMinutes}>
                      <Button
                        size="small"
                        icon={<CheckCircleOutlined />}
                        loading={approvingMinutes}
                      >
                        Approve
                      </Button>
                    </Popconfirm>
                  )}
                  {selectedAgenda.minutes?.approvedAt && (
                    <Tag color="green" icon={<CheckCircleOutlined />}>
                      Approved {dayjs(selectedAgenda.minutes.approvedAt).format('MMM D')}
                    </Tag>
                  )}
                </Space>
              }
            >
              {/* Notes */}
              <Text strong style={{ display: 'block', marginBottom: 4 }}>Notes</Text>
              <TextArea
                rows={4}
                value={minutesNotes}
                onChange={(e) => setMinutesNotes(e.target.value)}
                placeholder="Meeting notes..."
                style={{ marginBottom: 16 }}
              />

              {/* Decisions */}
              <Text strong style={{ display: 'block', marginBottom: 4 }}>Decisions</Text>
              <List
                size="small"
                dataSource={minutesDecisions}
                locale={{ emptyText: 'No decisions recorded' }}
                renderItem={(decision, index) => (
                  <List.Item
                    actions={[
                      <Switch
                        key="passed"
                        size="small"
                        checked={decision.passed}
                        onChange={() => handleToggleDecisionPassed(index)}
                        checkedChildren="Passed"
                        unCheckedChildren="Not passed"
                      />,
                      <Button
                        key="del"
                        size="small"
                        danger
                        type="text"
                        icon={<DeleteOutlined />}
                        onClick={() => handleRemoveDecision(index)}
                      />,
                    ]}
                  >
                    <Text>{decision.text}</Text>
                  </List.Item>
                )}
              />
              <Row gutter={8} style={{ marginTop: 8, marginBottom: 16 }}>
                <Col flex="auto">
                  <Input
                    size="small"
                    placeholder="Add a decision..."
                    value={newDecisionText}
                    onChange={(e) => setNewDecisionText(e.target.value)}
                    onPressEnter={handleAddDecision}
                  />
                </Col>
                <Col>
                  <Button size="small" icon={<PlusOutlined />} onClick={handleAddDecision}>
                    Add
                  </Button>
                </Col>
              </Row>

              {/* Attendees */}
              <Text strong style={{ display: 'block', marginBottom: 4 }}>Attendees</Text>
              <Space wrap style={{ marginBottom: 8 }}>
                {minutesAttendees.map((attendee, index) => (
                  <Tag
                    key={index}
                    closable
                    onClose={() => handleRemoveAttendee(index)}
                  >
                    {attendee.name}
                  </Tag>
                ))}
              </Space>
              <Row gutter={8}>
                <Col flex="auto">
                  <Input
                    size="small"
                    placeholder="Add attendee name..."
                    value={newAttendeeName}
                    onChange={(e) => setNewAttendeeName(e.target.value)}
                    onPressEnter={handleAddAttendee}
                  />
                </Col>
                <Col>
                  <Button size="small" icon={<PlusOutlined />} onClick={handleAddAttendee}>
                    Add
                  </Button>
                </Col>
              </Row>
            </Card>

            {/* Action Items */}
            <Card size="small" title={`Action Items (${selectedAgenda.actionItems?.length ?? 0})`}>
              <Table
                dataSource={selectedAgenda.actionItems || []}
                columns={actionItemColumns}
                scroll={{ x: 'max-content' }}
                rowKey="id"
                size="small"
                pagination={false}
                locale={{ emptyText: 'No action items' }}
              />
            </Card>
          </>
        )}
      </Drawer>
    </div>
  );
}
