'use client';
import { useEffect } from 'react';
import { useFlowmeChannelStore } from '../store/channel';
import { useForm } from 'react-hook-form';
import { pick } from 'es-toolkit';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Plus, Pencil, Trash2 } from 'lucide-react';

const TableList = () => {
  const { list, setShowEdit, setFormData, deleteData } = useFlowmeChannelStore();

  return (
    <div className="rounded-md border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>标题</TableHead>
            <TableHead>描述</TableHead>
            <TableHead>标签</TableHead>
            <TableHead>颜色</TableHead>
            <TableHead>操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {list.map((item) => (
            <TableRow key={item.id}>
              <TableCell>{item.title}</TableCell>
              <TableCell>{item.description}</TableCell>
              <TableCell>{item.tags?.join(', ')}</TableCell>
              <TableCell>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 rounded" style={{ backgroundColor: item.color }} />
                  {item.color}
                </div>
              </TableCell>
              <TableCell className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setShowEdit(true);
                    setFormData(item);
                  }}>
                  <Pencil className="w-4 h-4 mr-1" />
                  编辑
                </Button>
                <Button
                  variant="destructive"
                  size="sm"
                  onClick={() => deleteData(item.id)}>
                  <Trash2 className="w-4 h-4 mr-1" />
                  删除
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
};

const FormModal = () => {
  const { showEdit, setShowEdit, formData, updateData } = useFlowmeChannelStore();
  const {
    handleSubmit,
    reset,
    control,
  } = useForm();

  useEffect(() => {
    if (!showEdit) return;
    if (formData?.id) {
      reset(formData);
    } else {
      reset({
        title: '',
        description: '',
        color: '#007bff',
      });
    }
  }, [formData, showEdit, reset]);

  const onSubmit = async (data: any) => {
    const _formData: any = pick(data, ['title', 'description', 'tags', 'link', 'data', 'color']);
    if (formData.id) {
      _formData.id = formData.id;
    }
    const res = await updateData(_formData);
    if (res.code === 200) {
      setShowEdit(false);
    }
  };

  return (
    <Dialog open={showEdit} onOpenChange={setShowEdit}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{formData?.id ? '编辑' : '添加'}</DialogTitle>
        </DialogHeader>
        <div className="p-4">
          <form className="w-full flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium">标题</label>
              <Input
                {...control.register('title')}
                placeholder="请输入标题"
              />
            </div>
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium">描述</label>
              <Input
                {...control.register('description')}
                placeholder="请输入描述"
              />
            </div>
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium">颜色</label>
              <div className="flex gap-2">
                <Input
                  {...control.register('color')}
                  placeholder="请输入颜色值"
                />
                <Input
                  type="color"
                  {...control.register('color')}
                  className="w-12 h-10 p-1"
                />
              </div>
            </div>
            <Button type="submit">提交</Button>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export const List = () => {
  const { getList, setShowEdit, setFormData } = useFlowmeChannelStore();

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

  return (
    <div className="p-4 w-full h-full">
      <div className="flex mb-4">
        <Button
          onClick={() => {
            setShowEdit(true);
            setFormData({});
          }}>
          <Plus className="w-4 h-4 mr-1" />
          添加
        </Button>
      </div>
      <TableList />
      <FormModal />
    </div>
  );
};

export default List
