import {
  List,
  Avatar,
  Button,
  ButtonGroup,
  Typography,
  Tabs,
  TabPane,
  Toast,
} from '@douyinfe/semi-ui';
import { useNoteStore } from '../../stores/useNoteStore';
import noteService from '../../services/note.service';
import type { INote } from '../../types';

export default function HomePage() {
  const { homeData, setHomeData, setCurrentNote } = useNoteStore();

  const loadNote = (id: number) => {
    noteService.get(id).then(
      (res) => {
        const note = res.data;
        setCurrentNote(note.id, note.title, note.context);
      },
      () => Toast.error('加载笔记失败'),
    );
  };

  const handleTabChange = (key: string) => {
    noteService.getHomeData(key, '0').then(
      (res) => setHomeData(res.data),
      () => Toast.error('加载列表失败'),
    );
  };

  return (
    <>
      <Tabs type="button" onChange={handleTabChange} defaultActiveKey="1">
        <TabPane tab="最近更新" itemKey="1" />
        <TabPane tab="最新添加" itemKey="2" />
        <TabPane tab="最近浏览" itemKey="3" />
      </Tabs>
      <div style={{ padding: 5, border: '1px solid var(--semi-color-border)', margin: 5 }}>
        <List
          dataSource={homeData}
          renderItem={(item: INote) => (
            <List.Item
              header={<Avatar color="blue">NOTE</Avatar>}
              main={
                <div>
                  <span style={{ color: 'var(--semi-color-text-0)', fontWeight: 500 }}>
                    {item.title}
                  </span>
                  <Typography.Text
                    ellipsis={{ showTooltip: true }}
                    style={{ width: 'calc(100% - 68px)' }}
                  >
                    创建时间：{item.createtime}，更新时间：{item.updatetime}，
                    最后浏览时间：{item.viewtime}。
                  </Typography.Text>
                </div>
              }
              extra={
                <ButtonGroup theme="borderless">
                  <Button onClick={() => loadNote(item.id)}>查看</Button>
                </ButtonGroup>
              }
            />
          )}
        />
      </div>
    </>
  );
}
