import { useEffect, useMemo, useState } from 'react';
import { Button, Card, Col, DatePicker, Form, Input, Row, Segmented, Select, Space, Statistic, Table, Tag, message } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { request } from '@/request';
import { WorkflowPage } from './shared';
import { selectCurrentAdmin } from '@/redux/auth/selectors';
import { canAccessEntityAction } from '@/utils/permissions';

const STATUS_OPTIONS = [
  { value: 'todo', label: 'To Do', color: 'default' },
  { value: 'in_progress', label: 'In Progress', color: 'blue' },
  { value: 'done', label: 'Done', color: 'green' },
  { value: 'cancelled', label: 'Cancelled', color: 'red' },
];

const PRIORITY_OPTIONS = [
  { value: 'low', label: 'Low', color: 'default' },
  { value: 'normal', label: 'Normal', color: 'blue' },
  { value: 'high', label: 'High', color: 'orange' },
  { value: 'urgent', label: 'Urgent', color: 'red' },
];

const optionColor = (options, value) => options.find((item) => item.value === value)?.color || 'default';
const optionLabel = (options, value) => options.find((item) => item.value === value)?.label || value || '-';

export default function TaskBoard() {
  const [tasks, setTasks] = useState([]);
  const [form] = Form.useForm();
  const [filters, setFilters] = useState({ search: '', status: undefined, priority: undefined });
  const [viewMode, setViewMode] = useState('List');
  const [loading, setLoading] = useState(false);
  const location = useLocation();
  const currentAdmin = useSelector(selectCurrentAdmin);
  const canCreateTasks = canAccessEntityAction(currentAdmin, 'task', 'create');
  const canUpdateTasks = canAccessEntityAction(currentAdmin, 'task', 'update');

  const load = async () => {
    setLoading(true);
    const response = await request.list({ entity: 'task', options: { page: 1, items: 100 } });
    setTasks(response?.result || []);
    setLoading(false);
  };

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

  useEffect(() => {
    setViewMode(location.pathname.endsWith('/calendar') ? 'Calendar' : 'List');
  }, [location.pathname]);

  const save = async () => {
    const values = await form.validateFields();
    await request.create({
      entity: 'task',
      jsonData: {
        ...values,
        dueAt: values.dueAt?.toISOString?.(),
        status: values.status || 'todo',
      },
    });
    message.success('Task created');
    form.resetFields();
    load();
  };

  const updateTask = async (record, patch) => {
    await request.update({
      entity: 'task',
      id: record._id,
      jsonData: {
        ...patch,
        completedAt: patch.status === 'done' ? new Date().toISOString() : record.completedAt,
      },
    });
    message.success('Task updated');
    load();
  };

  const filteredTasks = useMemo(() => {
    const query = filters.search.trim().toLowerCase();
    return tasks.filter((task) => {
      if (filters.status && task.status !== filters.status) return false;
      if (filters.priority && task.priority !== filters.priority) return false;
      if (!query) return true;
      return [task.title, task.description, task.relatedTo?.entityType]
        .filter(Boolean)
        .some((value) => String(value).toLowerCase().includes(query));
    });
  }, [tasks, filters]);

  const taskStats = useMemo(() => {
    const open = tasks.filter((task) => !['done', 'cancelled'].includes(task.status)).length;
    const dueToday = tasks.filter((task) => task.dueAt && dayjs(task.dueAt).isSame(dayjs(), 'day') && task.status !== 'done').length;
    const overdue = tasks.filter((task) => task.dueAt && dayjs(task.dueAt).isBefore(dayjs(), 'day') && task.status !== 'done').length;
    const done = tasks.filter((task) => task.status === 'done').length;
    return { open, dueToday, overdue, done };
  }, [tasks]);

  const calendarTasks = useMemo(() => {
    return filteredTasks.reduce((acc, task) => {
      if (!task.dueAt) return acc;
      const key = dayjs(task.dueAt).format('YYYY-MM-DD');
      acc[key] = acc[key] || [];
      acc[key].push(task);
      return acc;
    }, {});
  }, [filteredTasks]);

  return (
    <WorkflowPage
      title="Task Management"
      description="Plan, assign, prioritize, and complete operational tasks created by users, automations, and AI Studio."
      permission="tasks.task.read"
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={load}>Refresh</Button>
          <Button type="primary" disabled={!canCreateTasks} onClick={save}>Create Task</Button>
        </Space>
      }
    >
      <Space direction="vertical" size={18} style={{ width: '100%' }}>
        <Row gutter={[16, 16]}>
          <Col xs={12} md={6}>
            <Card size="small">
              <Statistic title="Open Tasks" value={taskStats.open} prefix={<ClockCircleOutlined />} />
            </Card>
          </Col>
          <Col xs={12} md={6}>
            <Card size="small">
              <Statistic title="Due Today" value={taskStats.dueToday} />
            </Card>
          </Col>
          <Col xs={12} md={6}>
            <Card size="small">
              <Statistic title="Overdue" value={taskStats.overdue} valueStyle={{ color: taskStats.overdue ? '#cf1322' : undefined }} />
            </Card>
          </Col>
          <Col xs={12} md={6}>
            <Card size="small">
              <Statistic title="Completed" value={taskStats.done} prefix={<CheckCircleOutlined />} />
            </Card>
          </Col>
        </Row>

        <Card size="small" title="Create Task">
          <Form form={form} layout="vertical" initialValues={{ priority: 'normal', status: 'todo' }}>
            <Row gutter={12}>
              <Col xs={24} md={12}>
                <Form.Item name="title" label="Title" rules={[{ required: true }]}>
                  <Input placeholder="Call lead, review AI flyer, approve campaign..." />
                </Form.Item>
              </Col>
              <Col xs={24} md={6}>
                <Form.Item name="priority" label="Priority">
                  <Select options={PRIORITY_OPTIONS.map(({ value, label }) => ({ value, label }))} />
                </Form.Item>
              </Col>
              <Col xs={24} md={6}>
                <Form.Item name="dueAt" label="Due Date">
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="description" label="Description">
                  <Input.TextArea rows={3} placeholder="Add context, handoff notes, linked campaign details, or approval instructions." />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card size="small">
          <Space wrap style={{ marginBottom: 12 }}>
            <Segmented value={viewMode} onChange={setViewMode} options={['List', 'Calendar']} />
            <Input.Search
              allowClear
              placeholder="Search tasks"
              style={{ width: 260 }}
              onChange={(event) => setFilters((current) => ({ ...current, search: event.target.value }))}
            />
            <Select
              allowClear
              placeholder="Status"
              style={{ width: 160 }}
              value={filters.status}
              onChange={(value) => setFilters((current) => ({ ...current, status: value }))}
              options={STATUS_OPTIONS.map(({ value, label }) => ({ value, label }))}
            />
            <Select
              allowClear
              placeholder="Priority"
              style={{ width: 160 }}
              value={filters.priority}
              onChange={(value) => setFilters((current) => ({ ...current, priority: value }))}
              options={PRIORITY_OPTIONS.map(({ value, label }) => ({ value, label }))}
            />
          </Space>
          {viewMode === 'Calendar' ? (
            <DatePicker.Calendar
              fullscreen={false}
              cellRender={(current) => {
                const dayTasks = calendarTasks[current.format('YYYY-MM-DD')] || [];
                return (
                  <Space direction="vertical" size={2} style={{ width: '100%' }}>
                    {dayTasks.slice(0, 3).map((task) => (
                      <Tag key={task._id} color={optionColor(PRIORITY_OPTIONS, task.priority)} style={{ marginInlineEnd: 0, maxWidth: '100%' }}>
                        {task.title}
                      </Tag>
                    ))}
                    {dayTasks.length > 3 ? <Tag>+{dayTasks.length - 3} more</Tag> : null}
                  </Space>
                );
              }}
            />
          ) : (
            <Table
              rowKey="_id"
              loading={loading}
              dataSource={filteredTasks}
              pagination={{ pageSize: 10 }}
              columns={[
                {
                  title: 'Task',
                  dataIndex: 'title',
                  render: (value, record) => (
                    <Space direction="vertical" size={0}>
                      <strong>{value}</strong>
                      <span style={{ color: '#64748b' }}>{record.description || 'No description'}</span>
                    </Space>
                  ),
                },
                {
                  title: 'Priority',
                  dataIndex: 'priority',
                  render: (value) => <Tag color={optionColor(PRIORITY_OPTIONS, value)}>{optionLabel(PRIORITY_OPTIONS, value)}</Tag>,
                },
                {
                  title: 'Status',
                  dataIndex: 'status',
                  render: (value, record) => (
                    <Select
                      size="small"
                      disabled={!canUpdateTasks}
                      value={value || 'todo'}
                      style={{ width: 140 }}
                      onChange={(status) => updateTask(record, { status })}
                      options={STATUS_OPTIONS.map(({ value: optionValue, label }) => ({ value: optionValue, label }))}
                    />
                  ),
                },
                {
                  title: 'Due',
                  dataIndex: 'dueAt',
                  render: (value) =>
                    value ? (
                      <Tag color={dayjs(value).isBefore(dayjs(), 'day') ? 'red' : dayjs(value).isSame(dayjs(), 'day') ? 'orange' : 'blue'}>
                        {dayjs(value).format('MMM D, YYYY')}
                      </Tag>
                    ) : (
                      '-'
                    ),
                },
                {
                  title: 'Linked Record',
                  dataIndex: 'relatedTo',
                  render: (value) => value?.entityType || '-',
                },
                {
                  title: 'Action',
                  render: (_, record) => (
                    <Space>
                      <Button size="small" disabled={!canUpdateTasks || record.status === 'in_progress'} onClick={() => updateTask(record, { status: 'in_progress' })}>
                        Start
                      </Button>
                      <Button size="small" type="primary" disabled={!canUpdateTasks || record.status === 'done'} onClick={() => updateTask(record, { status: 'done' })}>
                        Done
                      </Button>
                    </Space>
                  ),
                },
              ]}
            />
          )}
        </Card>
      </Space>
    </WorkflowPage>
  );
}
