import { useEffect } from 'react';
import { appDomainStatus, useDomainStore } from '../store';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  Modal,
  TextField,
  Dialog,
  DialogContent,
  DialogTitle,
  useTheme,
} from '@mui/material';
import { useForm, Controller } from 'react-hook-form';
import { pick } from 'lodash-es';
import { Select } from '@kevisual/components/select/index.tsx';

const TableList = () => {
  const { list, setList, getDomainList, updateDomain, setShowEditModal, setFormData, deleteDomain } = useDomainStore();
  useEffect(() => {
    getDomainList();
  }, []);

  return (
    <TableContainer component={Paper}>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>ID</TableCell>
            <TableCell>Domain</TableCell>
            <TableCell>App ID</TableCell>
            <TableCell>UID</TableCell>
            <TableCell>Status</TableCell>
            <TableCell>操作</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {list.map((domain) => (
            <TableRow key={domain.id}>
              <TableCell>{domain.id}</TableCell>
              <TableCell>{domain.domain}</TableCell>
              <TableCell>{domain.appId}</TableCell>
              <TableCell>{domain.uid}</TableCell>
              <TableCell>{domain.status}</TableCell>
              <TableCell>
                <Button
                  variant='contained'
                  color='primary'
                  onClick={() => {
                    setShowEditModal(true);
                    setFormData(domain);
                  }}>
                  编辑
                </Button>
                <Button variant='contained' color='error' onClick={() => deleteDomain(domain)}>
                  删除
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

const FomeModal = () => {
  const { showEditModal, setShowEditModal, formData, updateDomain } = useDomainStore();
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    getValues,
    setValue,
    control,
  } = useForm();
  useEffect(() => {
    if (!showEditModal) return;
    if (formData?.id) {
      reset(formData);
    } else {
      reset({
        status: 'running',
      });
    }
  }, [formData]);
  const onSubmit = async (data: any) => {
    // 处理表单提交逻辑
    const _formData = pick(data, ['domain', 'appId', 'status', 'id']);
    if (formData.id) {
      _formData.id = formData.id;
    }
    const res = await updateDomain(_formData);
    if (res.code === 200) {
      setShowEditModal(false);
    }
  };
  const theme = useTheme();
  const defultProps = theme.components?.MuiTextField?.defaultProps;
  return (
    <Dialog open={showEditModal} onClose={() => setShowEditModal(false)}>
      <DialogTitle>添加域名</DialogTitle>
      <DialogContent>
        <div className='p-4 w-[500px]'>
          <form className='w-full h-full flex flex-col gap-4' onSubmit={handleSubmit(onSubmit)}>
            <Controller
              name='domain'
              control={control}
              defaultValue=''
              rules={{ required: 'Domain is required' }}
              render={({ field }) => <TextField {...defultProps} label='Domain' {...field} error={!!errors.domain} />}
            />
            <Controller
              name='appId'
              control={control}
              defaultValue=''
              rules={{ required: 'App ID is required' }}
              render={({ field }) => <TextField {...defultProps} label='App ID' {...field} error={!!errors.appId} />}
            />
            <Controller
              name='status'
              control={control}
              defaultValue=''
              render={({ field }) => (
                <Select
                  {...field}
                  options={[
                    ...appDomainStatus.map((item) => ({
                      label: item,
                      value: item,
                    })),
                  ]}
                  error={!!errors.status}
                />
              )}
            />
            <Button type='submit' variant='contained' color='primary'>
              提交
            </Button>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export const List = () => {
  const { setShowEditModal, setFormData } = useDomainStore();
  return (
    <div className='p-4 w-full h-full bg-amber-900'>
      <div className='flex'>
        <Button
          variant='contained'
          color='primary'
          onClick={() => {
            setShowEditModal(true);
            setFormData({});
          }}>
          添加
        </Button>
      </div>
      <div>
        <TableList />
      </div>
      <FomeModal />
    </div>
  );
};
