import { useMemo, useState } from 'react'
import { Button, Card, Grid, Space, Tag, Typography } from '@arco-design/web-react'
import { IconCheckCircleFill, IconClockCircle, IconFile, IconLink } from '@arco-design/web-react/icon'
import { ProjectFileGrid } from './project-file-grid'
import { ProjectTaskEditModal, type ProjectTaskUpdate } from './project-task-edit-modal'
import type { ProjectWorkspace, TaskItem } from './project-types'

const { Row, Col } = Grid
const { Title, Text, Paragraph } = Typography

export function ProjectOverview({
  activeWorkspace,
  onSelectItem,
  onUpdateTask,
}: {
  activeWorkspace: ProjectWorkspace
  onSelectItem: (title: string) => void
  onUpdateTask: (update: ProjectTaskUpdate) => void
}) {
  const { project, tasks, notes, cronJobs } = activeWorkspace
  const runningTasks = useMemo(() => tasks.filter((task) => !task.completed), [tasks])
  const completedTasks = useMemo(() => tasks.filter((task) => task.completed), [tasks])
  const [editingTask, setEditingTask] = useState<TaskItem | null>(null)
  const shareURL = useMemo(() => projectShareURL(project.identifier || project.id), [project.id, project.identifier])
  const metrics = useMemo(() => [
    { title: '进行中的任务', value: runningTasks.length, icon: <IconCheckCircleFill />, color: 'green' },
    { title: '完成的任务', value: completedTasks.length, icon: <IconCheckCircleFill />, color: 'arcoblue' },
    { title: '笔记资料总数', value: notes.length, icon: <IconFile />, color: 'cyan' },
    { title: '计划任务', value: cronJobs.length, icon: <IconClockCircle />, color: 'orange' },
  ], [completedTasks.length, cronJobs.length, notes.length, runningTasks.length])

  return (
    <div className="overview-page project-overview-page">
      <section className="project-overview-hero" style={{ background: projectHeroBackground(project.background, project.color) }}>
        <div className="project-overview-identity">
          <span className="project-overview-icon">{project.short}</span>
          <div>
            <Title heading={3}>{project.name}</Title>
            <Paragraph ellipsis={{ rows: 2 }}>{project.description || '暂无简介'}</Paragraph>
          </div>
        </div>
        <div className="project-overview-share">
          <Text>项目 URL</Text>
          <Button icon={<IconLink />} onClick={() => onSelectItem(shareURL)}>{shareURL}</Button>
        </div>
      </section>

      <Row gutter={12} className="metric-row">
        {metrics.map((metric) => (
          <Col span={6} key={metric.title}>
            <Card className="metric-card" bordered>
              <Space align="start">
                <Tag color={metric.color}>{metric.icon}</Tag>
                <div>
                  <Text type="secondary">{metric.title}</Text>
                  <Title heading={3}>{metric.value}</Title>
                  <Text className="metric-delta">当前统计</Text>
                </div>
              </Space>
            </Card>
          </Col>
        ))}
      </Row>

      <TaskCardSection title={`进行中的任务（${runningTasks.length}）`} tasks={runningTasks} emptyText="当前没有进行中的任务" onEditTask={setEditingTask} />
      <TaskCardSection title={`完成的任务（${completedTasks.length}）`} tasks={completedTasks} emptyText="当前没有完成的任务" onSelectItem={onSelectItem} />
      <NoteSection notes={notes} onSelectItem={onSelectItem} />
      <ProjectTaskEditModal
        task={editingTask}
        workspace={activeWorkspace}
        onClose={() => setEditingTask(null)}
        onSubmit={(update) => {
          onUpdateTask(update)
          setEditingTask(null)
        }}
      />
    </div>
  )
}

function TaskCardSection({
  title,
  tasks,
  emptyText,
  onSelectItem,
  onEditTask,
}: {
  title: string
  tasks: TaskItem[]
  emptyText: string
  onSelectItem?: (title: string) => void
  onEditTask?: (task: TaskItem) => void
}) {
  return (
    <Card className="queue-section overview-task-section" bordered>
      <div className="section-header">
        <Title heading={6}>{title}</Title>
        <Button type="text" size="mini">查看全部</Button>
      </div>
      {tasks.length === 0 ? (
        <Text type="secondary">{emptyText}</Text>
      ) : (
        <div className="overview-task-grid">
          {tasks.map((task) => (
            <button key={task.id} className={task.completed ? 'overview-task-card completed' : 'overview-task-card'} onClick={() => onEditTask ? onEditTask(task) : onSelectItem?.(task.title)}>
              <span className="overview-task-title">
                <IconCheckCircleFill />
                {task.title}
              </span>
              <Text type="secondary" ellipsis={{ showTooltip: true }}>{task.summary || '暂无任务内容'}</Text>
              <div className="overview-task-meta">
                <Tag color={task.completed ? 'green' : 'arcoblue'}>{task.tag || (task.completed ? '已完成' : '进行中')}</Tag>
                <span>进度 {task.progress}</span>
                <span>创建 {task.createdAt}</span>
              </div>
            </button>
          ))}
        </div>
      )}
    </Card>
  )
}

function NoteSection({ notes, onSelectItem }: { notes: ProjectWorkspace['notes']; onSelectItem: (title: string) => void }) {
  return (
    <Card className="queue-section" bordered>
      <div className="section-header">
        <Title heading={6}>最近笔记资料（{notes.length}）</Title>
        <Button type="text" size="mini">查看全部</Button>
      </div>
      <ProjectFileGrid items={notes.slice(0, 8)} onSelectItem={onSelectItem} compact />
    </Card>
  )
}

function projectShareURL(identifier: string) {
  const slug = encodeURIComponent(identifier.trim() || 'project')
  const origin = typeof window === 'undefined' ? 'https://senlinai.local' : window.location.origin
  return `${origin}/share/projects/${slug}`
}

function projectHeroBackground(background: string, fallback: string) {
  const value = background.trim() || fallback
  if (value.startsWith('http')) {
    return `linear-gradient(135deg, color-mix(in srgb, ${fallback} 78%, transparent), color-mix(in srgb, ${fallback} 34%, transparent)), url("${value.replaceAll('"', '%22')}") center / cover`
  }
  if (value.startsWith('linear-gradient') || value.startsWith('radial-gradient')) {
    return value
  }
  return `linear-gradient(135deg, ${value}, color-mix(in srgb, ${value} 58%, white))`
}
