import React, { useState } from 'react';
import {
  Card,
  Upload,
  Button,
  message,
  Table,
  Tag,
  Space,
  Modal,
  Image,
  Progress,
  Divider,
  Row,
  Col,
  Input,
  Select,
  Tooltip,
  Alert,
  Tabs,
} from 'antd';
import {
  UploadOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
  FolderOutlined,
  FileImageOutlined,
  FileOutlined,
  VideoCameraOutlined,
  ReloadOutlined,
  SearchOutlined,
  FilterOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { productDataSource, Product } from '@/services/productDataSource';

const { Option } = Select;
const { TabPane } = Tabs;

interface MaterialFile {
  id: string;
  name: string;
  type: 'image' | 'video' | 'document';
  size: number;
  url: string;
  thumbnail?: string;
  uploadedAt: string;
  uploadedBy: string;
  status: 'READY' | 'PROCESSING' | 'FAILED';
  tags: string[];
  productId?: string;
  productName?: string;
}

const MOCK_MATERIALS: MaterialFile[] = [
  {
    id: '1',
    name: 'product_main_001.jpg',
    type: 'image',
    size: 2456789,
    url: 'https://via.placeholder.com/800x800?text=Product+1',
    thumbnail: 'https://via.placeholder.com/100x100?text=1',
    uploadedAt: '2026-03-18 10:30:00',
    uploadedBy: 'Admin',
    status: 'READY',
    tags: ['main', 'product'],
    productId: 'P-2026-001',
    productName: 'Industrial Sensor A',
  },
  {
    id: '2',
    name: 'product_gallery_002.jpg',
    type: 'image',
    size: 1890234,
    url: 'https://via.placeholder.com/800x800?text=Product+2',
    thumbnail: 'https://via.placeholder.com/100x100?text=2',
    uploadedAt: '2026-03-18 10:35:00',
    uploadedBy: 'Admin',
    status: 'READY',
    tags: ['gallery', 'product'],
    productId: 'P-2026-001',
    productName: 'Industrial Sensor A',
  },
  {
    id: '3',
    name: 'product_video_demo.mp4',
    type: 'video',
    size: 15678901,
    url: 'https://example.com/video.mp4',
    thumbnail: 'https://via.placeholder.com/100x100?text=Video',
    uploadedAt: '2026-03-17 14:00:00',
    uploadedBy: 'Operator',
    status: 'PROCESSING',
    tags: ['demo', 'video'],
  },
  {
    id: '4',
    name: 'product_manual.pdf',
    type: 'document',
    size: 567890,
    url: 'https://example.com/manual.pdf',
    uploadedAt: '2026-03-16 09:00:00',
    uploadedBy: 'Admin',
    status: 'READY',
    tags: ['manual', 'document'],
    productId: 'P-2026-002',
    productName: 'Control Module B',
  },
];

const TYPE_CONFIG: Record<string, { color: string; icon: React.ReactNode }> = {
  image: { color: 'blue', icon: <FileImageOutlined /> },
  video: { color: 'purple', icon: <VideoCameraOutlined /> },
  document: { color: 'green', icon: <FileOutlined /> },
};

const STATUS_CONFIG: Record<string, { color: string; text: string }> = {
  READY: { color: 'success', text: 'Ready' },
  PROCESSING: { color: 'processing', text: 'Processing' },
  FAILED: { color: 'error', text: 'Failed' },
};

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

export const MaterialUpload: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [materials, setMaterials] = useState<MaterialFile[]>(MOCK_MATERIALS);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewFile, setPreviewFile] = useState<MaterialFile | null>(null);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<string>('all');

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('Please select files to upload');
      return;
    }

    setUploading(true);
    setUploadProgress(0);

    for (let i = 0; i <= 100; i += 10) {
      await new Promise(resolve => setTimeout(resolve, 200));
      setUploadProgress(i);
    }

    const newMaterials: MaterialFile[] = fileList.map((file, index) => ({
      id: `${Date.now()}-${index}`,
      name: file.name,
      type: file.type?.startsWith('image') ? 'image' : 
            file.type?.startsWith('video') ? 'video' : 'document',
      size: file.size || 0,
      url: URL.createObjectURL(file as any),
      thumbnail: file.type?.startsWith('image') ? URL.createObjectURL(file as any) : undefined,
      uploadedAt: new Date().toISOString(),
      uploadedBy: 'Current User',
      status: 'READY',
      tags: [],
    }));

    setMaterials([...newMaterials, ...materials]);
    setFileList([]);
    setUploading(false);
    message.success(`${fileList.length} file(s) uploaded successfully`);
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: 'Delete Material',
      content: 'Are you sure you want to delete this file?',
      okText: 'Delete',
      okType: 'danger',
      onOk: () => {
        setMaterials(materials.filter(m => m.id !== id));
        message.success('File deleted');
      },
    });
  };

  const handlePreview = (file: MaterialFile) => {
    setPreviewFile(file);
    setPreviewVisible(true);
  };

  const handleCopyUrl = (url: string) => {
    navigator.clipboard.writeText(url);
    message.success('URL copied to clipboard');
  };

  const getFilteredMaterials = () => {
    return materials.filter(m => {
      const matchesSearch = m.name.toLowerCase().includes(searchText.toLowerCase()) ||
                           m.tags.some(t => t.toLowerCase().includes(searchText.toLowerCase()));
      const matchesType = filterType === 'all' || m.type === filterType;
      return matchesSearch && matchesType;
    });
  };

  const columns = [
    {
      title: 'Preview',
      dataIndex: 'thumbnail',
      key: 'thumbnail',
      width: 80,
      render: (_: any, record: MaterialFile) => (
        record.type === 'image' ? (
          <Image
            src={record.thumbnail}
            alt={record.name}
            width={50}
            height={50}
            style={{ objectFit: 'cover', borderRadius: 4 }}
          />
        ) : (
          <div style={{ width: 50, height: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f5f5f5', borderRadius: 4 }}>
            {TYPE_CONFIG[record.type].icon}
          </div>
        )
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: MaterialFile) => (
        <Space>
          <Tag color={TYPE_CONFIG[record.type].color} icon={TYPE_CONFIG[record.type].icon}>
            {record.type.toUpperCase()}
          </Tag>
          <span>{name}</span>
        </Space>
      ),
    },
    {
      title: 'Size',
      dataIndex: 'size',
      key: 'size',
      width: 100,
      render: (size: number) => formatFileSize(size),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={STATUS_CONFIG[status].color}>{STATUS_CONFIG[status].text}</Tag>
      ),
    },
    {
      title: 'Product',
      dataIndex: 'productName',
      key: 'productName',
      width: 150,
      render: (name: string) => name || <Tag>Unassigned</Tag>,
    },
    {
      title: 'Uploaded',
      dataIndex: 'uploadedAt',
      key: 'uploadedAt',
      width: 150,
    },
    {
      title: 'Tags',
      dataIndex: 'tags',
      key: 'tags',
      width: 150,
      render: (tags: string[]) => tags.map(t => <Tag key={t}>{t}</Tag>),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 120,
      render: (_: any, record: MaterialFile) => (
        <Space>
          <Tooltip title="Preview">
            <Button type="text" icon={<EyeOutlined />} onClick={() => handlePreview(record)} />
          </Tooltip>
          <Tooltip title="Copy URL">
            <Button type="text" icon={<CopyOutlined />} onClick={() => handleCopyUrl(record.url)} />
          </Tooltip>
          <Tooltip title="Delete">
            <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const stats = {
    total: materials.length,
    images: materials.filter(m => m.type === 'image').length,
    videos: materials.filter(m => m.type === 'video').length,
    documents: materials.filter(m => m.type === 'document').length,
    totalSize: materials.reduce((acc, m) => acc + m.size, 0),
  };

  return (
    <div className="material-upload-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <FolderOutlined style={{ fontSize: 32, color: '#1890ff' }} />
              <div>
                <div style={{ color: '#666' }}>Total Files</div>
                <div style={{ fontSize: 24, fontWeight: 'bold' }}>{stats.total}</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <FileImageOutlined style={{ fontSize: 32, color: '#52c41a' }} />
              <div>
                <div style={{ color: '#666' }}>Images</div>
                <div style={{ fontSize: 24, fontWeight: 'bold' }}>{stats.images}</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <VideoCameraOutlined style={{ fontSize: 32, color: '#722ed1' }} />
              <div>
                <div style={{ color: '#666' }}>Videos</div>
                <div style={{ fontSize: 24, fontWeight: 'bold' }}>{stats.videos}</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <FileOutlined style={{ fontSize: 32, color: '#fa8c16' }} />
              <div>
                <div style={{ color: '#666' }}>Total Size</div>
                <div style={{ fontSize: 24, fontWeight: 'bold' }}>{formatFileSize(stats.totalSize)}</div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      <Card title="Upload Materials">
        <Tabs defaultActiveKey="upload">
          <TabPane tab="Upload" key="upload">
            <Alert
              message="Upload Guidelines"
              description="Supported formats: JPG, PNG, GIF, MP4, PDF. Maximum file size: 50MB per file. Recommended image resolution: 1000x1000 pixels or higher."
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />

            <Upload
              multiple
              fileList={fileList}
              onChange={({ fileList }) => setFileList(fileList)}
              beforeUpload={() => false}
              listType="picture"
            >
              <Button icon={<UploadOutlined />}>Select Files</Button>
            </Upload>

            {uploading && (
              <div style={{ marginTop: 16 }}>
                <Progress percent={uploadProgress} status="active" />
              </div>
            )}

            <Divider />

            <Space>
              <Button
                type="primary"
                onClick={handleUpload}
                disabled={fileList.length === 0}
                loading={uploading}
              >
                Start Upload
              </Button>
              <Button onClick={() => setFileList([])} disabled={fileList.length === 0}>
                Clear
              </Button>
            </Space>
          </TabPane>

          <TabPane tab="Library" key="library">
            <Space style={{ marginBottom: 16 }}>
              <Input
                placeholder="Search by name or tag"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 250 }}
              />
              <Select value={filterType} onChange={setFilterType} style={{ width: 120 }}>
                <Option value="all">All Types</Option>
                <Option value="image">Images</Option>
                <Option value="video">Videos</Option>
                <Option value="document">Documents</Option>
              </Select>
              <Button icon={<ReloadOutlined />} onClick={() => { setSearchText(''); setFilterType('all'); }}>
                Reset
              </Button>
            </Space>

            <Table
              columns={columns}
              dataSource={getFilteredMaterials()}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title="File Preview"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        {previewFile && (
          <div>
            {previewFile.type === 'image' ? (
              <Image src={previewFile.url} style={{ width: '100%' }} />
            ) : (
              <div style={{ textAlign: 'center', padding: 40 }}>
                {TYPE_CONFIG[previewFile.type].icon}
                <p style={{ marginTop: 16 }}>{previewFile.name}</p>
                <p style={{ color: '#666' }}>{formatFileSize(previewFile.size)}</p>
                <Button type="primary" href={previewFile.url} target="_blank">
                  Open File
                </Button>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default MaterialUpload;
