import { useState } from 'react';
import { Button, List, Progress, Space, Typography, Upload, message } from 'antd';
import { IconFile, IconTrash, IconUpload } from '@tabler/icons-react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { attachmentApi, AttachmentMeta } from '@/api/attachment';
import { GRAY, RADIUS, SHADOW, COLOR_ERROR } from '@/theme/tokens';

const { Text } = Typography;
const { Dragger } = Upload;

interface Props {
  refType: string;
  refId: number;
}

/**
 * 공용 첨부파일 업로드/목록/삭제 컴포넌트.
 * refType + refId 로 연결. Drag+Drop 지원.
 */
export default function AttachmentUpload({ refType, refId }: Props) {
  const qc = useQueryClient();
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);

  const { data: files = [], isLoading } = useQuery({
    queryKey: ['attachments', refType, refId],
    queryFn: () => attachmentApi.list(refType, refId),
    enabled: !!refId,
  });

  const handleUpload = async (file: File) => {
    setUploading(true);
    setProgress(0);
    try {
      await attachmentApi.upload(refType, refId, file, setProgress);
      message.success(`${file.name} 업로드 완료`);
      qc.invalidateQueries({ queryKey: ['attachments', refType, refId] });
    } catch {
      message.error('업로드 실패');
    } finally {
      setUploading(false);
      setProgress(0);
    }
    return false; // prevent antd auto-upload
  };

  const handleDelete = async (id: number, name: string) => {
    try {
      await attachmentApi.delete(id);
      message.success(`${name} 삭제 완료`);
      qc.invalidateQueries({ queryKey: ['attachments', refType, refId] });
    } catch {
      message.error('삭제 실패');
    }
  };

  const fmtSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
    return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
  };

  return (
    <div>
      <Dragger
        multiple={false}
        showUploadList={false}
        beforeUpload={handleUpload}
        disabled={uploading}
        style={{
          borderRadius: RADIUS.md,
          borderColor: GRAY[200],
          background: GRAY[50],
          padding: '12px 0',
        }}
      >
        <p style={{ margin: 0, color: GRAY[500], fontSize: 13 }}>
          <IconUpload size={20} style={{ verticalAlign: 'middle', marginRight: 8 }} />
          파일을 드래그하거나 클릭하여 업로드 (최대 50MB)
        </p>
      </Dragger>

      {uploading && (
        <Progress percent={progress} status="active" style={{ marginTop: 8 }} />
      )}

      {!isLoading && files.length > 0 && (
        <List
          size="small"
          style={{
            marginTop: 12,
            background: '#fff',
            border: `1px solid ${GRAY[100]}`,
            borderRadius: RADIUS.md,
            boxShadow: SHADOW.sm,
          }}
          dataSource={files}
          renderItem={(f: AttachmentMeta) => (
            <List.Item
              actions={[
                <Button
                  key="del"
                  type="text"
                  size="small"
                  icon={<IconTrash size={14} />}
                  style={{ color: COLOR_ERROR }}
                  onClick={() => handleDelete(f.attachmentId, f.originalName)}
                />,
              ]}
            >
              <Space>
                <IconFile size={14} style={{ color: GRAY[400] }} />
                <Text style={{ fontSize: 13 }}>{f.originalName}</Text>
                <Text style={{ fontSize: 12, color: GRAY[400] }}>({fmtSize(f.fileSize)})</Text>
              </Space>
            </List.Item>
          )}
        />
      )}
    </div>
  );
}
