import { useState, useEffect, useCallback } from 'react';
import { Table, Button, Space, App, Drawer, Form, Input, InputNumber, Select, Switch, Tag, Popconfirm, Grid, Radio, Image } from 'antd';
import { PlusOutlined, SyncOutlined, EditOutlined, DeleteOutlined, PictureOutlined, VideoCameraOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useNavigate, useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import { useSettingsStore } from '@/stores/settings.store';
import { PhotoPickerModal } from '@/components/media/PhotoPickerModal';
import type { Photo } from '@/components/media/PhotoPickerModal';
import { VideoPickerModal } from '@/components/media/VideoPickerModal';
import type { Video } from '@/components/media/VideoPickerModal';
import type { Product, PaginationMeta, ProductType, AppOutletContext } from '@/types/api';


export default function ProductsPage() {
  const navigate = useNavigate();
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [products, setProducts] = useState<Product[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [pagination, setPagination] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const { settings } = useSettingsStore();
  const mediaEnabled = settings?.enableMediaFeatures !== false;

  // Image source toggle: 'gallery' or 'url'
  const [imageSource, setImageSource] = useState<'gallery' | 'url'>('url');
  // Selected photo from gallery picker
  const [selectedPhoto, setSelectedPhoto] = useState<{ id: number; thumbnailUrl: string } | null>(null);
  // Selected promotional video
  const [selectedVideo, setSelectedVideo] = useState<{ id: number; title: string } | null>(null);
  // Gallery photos array
  const [galleryPhotos, setGalleryPhotos] = useState<Array<{ id: number; thumbnailUrl: string }>>([]);
  // Modal visibility
  const [photoPickerOpen, setPhotoPickerOpen] = useState(false);
  const [videoPickerOpen, setVideoPickerOpen] = useState(false);
  const [galleryPickerOpen, setGalleryPickerOpen] = useState(false);

  const fetchProducts = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const { data } = await api.get('/payments/admin/products', { params: { page, limit: 20 } });
      setProducts(data.products);
      setPagination(data.pagination);
    } catch {
      message.error('Failed to load products');
    } finally {
      setLoading(false);
    }
  }, [message]);

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

  useEffect(() => {
    setPageHeader({ title: 'Products' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const resetPickerState = () => {
    setImageSource('url');
    setSelectedPhoto(null);
    setSelectedVideo(null);
    setGalleryPhotos([]);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // Convert price to cents
      values.priceCAD = Math.round(values.priceCAD * 100);

      // Set media fields based on image source toggle
      if (imageSource === 'gallery') {
        values.photoId = selectedPhoto?.id ?? null;
        values.imageUrl = null; // clear external URL when using gallery
      } else {
        values.photoId = null; // clear gallery photo when using URL
      }

      values.videoId = selectedVideo?.id ?? null;
      values.galleryPhotoIds = galleryPhotos.length > 0 ? galleryPhotos.map((p) => p.id) : null;

      if (editingProduct) {
        await api.put(`/payments/admin/products/${editingProduct.id}`, values);
        message.success('Product updated');
      } else {
        await api.post('/payments/admin/products', values);
        message.success('Product created');
      }
      setDrawerOpen(false);
      form.resetFields();
      setEditingProduct(null);
      resetPickerState();
      fetchProducts(pagination.page);
    } catch {
      message.error('Failed to save product');
    }
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    form.setFieldsValue({
      ...product,
      priceCAD: product.priceCAD / 100,
    });

    // Restore picker state from product data
    if (product.photoId) {
      setImageSource('gallery');
      setSelectedPhoto({
        id: product.photoId,
        thumbnailUrl: product.thumbnailUrl || `/media/public/photos/${product.photoId}/thumbnail`,
      });
    } else {
      setImageSource('url');
      setSelectedPhoto(null);
    }

    if (product.videoId) {
      setSelectedVideo({ id: product.videoId, title: `Video #${product.videoId}` });
    } else {
      setSelectedVideo(null);
    }

    if (product.galleryPhotoIds && product.galleryPhotoIds.length > 0) {
      setGalleryPhotos(product.galleryPhotoIds.map((id) => ({
        id,
        thumbnailUrl: `/media/public/photos/${id}/thumbnail`,
      })));
    } else {
      setGalleryPhotos([]);
    }

    setDrawerOpen(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/payments/admin/products/${id}`);
      message.success('Product deleted');
      fetchProducts(pagination.page);
    } catch {
      message.error('Failed to delete product');
    }
  };

  const handleSyncStripe = async (id: string) => {
    try {
      await api.post(`/payments/admin/products/${id}/sync-stripe`);
      message.success('Synced to Stripe');
      fetchProducts(pagination.page);
    } catch {
      message.error('Failed to sync to Stripe');
    }
  };

  const handlePhotoSelect = (photo: Photo) => {
    setSelectedPhoto({
      id: photo.id,
      thumbnailUrl: photo.thumbnailUrl || `/media/public/photos/${photo.id}/thumbnail`,
    });
  };

  const handleVideoSelect = (video: Video) => {
    setSelectedVideo({ id: video.id, title: video.title });
  };

  const handleGalleryPhotoSelect = (photo: Photo) => {
    setGalleryPhotos((prev) => {
      // Avoid duplicates
      if (prev.some((p) => p.id === photo.id)) return prev;
      return [...prev, {
        id: photo.id,
        thumbnailUrl: photo.thumbnailUrl || `/media/public/photos/${photo.id}/thumbnail`,
      }];
    });
  };

  const typeColors: Record<ProductType, string> = {
    DIGITAL: 'blue',
    EVENT: 'green',
    DONATION: 'purple',
  };

  const columns = [
    {
      title: '',
      key: 'thumb',
      width: 56,
      render: (_: unknown, r: Product) => {
        const src = r.resolvedImageUrl || r.thumbnailUrl || r.imageUrl;
        return src ? (
          <img
            src={src}
            alt=""
            style={{ width: 48, height: 36, objectFit: 'cover', borderRadius: 4, display: 'block' }}
          />
        ) : (
          <div style={{ width: 48, height: 36, borderRadius: 4, background: 'rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <PictureOutlined style={{ opacity: 0.3 }} />
          </div>
        );
      },
    },
    { title: 'Title', dataIndex: 'title', key: 'title' },
    { title: 'Slug', dataIndex: 'slug', key: 'slug' },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      render: (t: ProductType) => <Tag color={typeColors[t]}>{t}</Tag>,
    },
    {
      title: 'Price',
      dataIndex: 'priceCAD',
      key: 'price',
      render: (v: number) => `$${(v / 100).toFixed(2)}`,
    },
    {
      title: 'Sales',
      key: 'sales',
      render: (_: unknown, r: Product) => r.maxPurchases ? `${r.purchaseCount}/${r.maxPurchases}` : r.purchaseCount,
    },
    {
      title: 'Active',
      dataIndex: 'isActive',
      key: 'active',
      render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? 'Active' : 'Inactive'}</Tag>,
    },
    {
      title: 'Stripe',
      key: 'stripe',
      render: (_: unknown, r: Product) => r.stripeProductId
        ? <Tag color="green">Synced</Tag>
        : <Tag>Not synced</Tag>,
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, r: Product) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(r)} />
          <Button size="small" icon={<SyncOutlined />} onClick={() => handleSyncStripe(r.id)} title="Sync to Stripe" />
          <Button size="small" icon={<PictureOutlined />} onClick={() => navigate('/app/payments/ads')} title="View Gallery Ad" />
          <Popconfirm title="Delete this product?" onConfirm={() => handleDelete(r.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const drawerWidth = isMobile ? 0 : 600;

  return (
    <>
      <div style={{ marginRight: drawerOpen ? drawerWidth : 0, transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingProduct(null);
              form.resetFields();
              resetPickerState();
              setDrawerOpen(true);
            }}
          >
            Add Product
          </Button>
        </div>

        <Table
          dataSource={products}
          columns={columns}
          rowKey="id"
          loading={loading}
          scroll={{ x: 'max-content' }}
          pagination={{
            current: pagination.page,
            pageSize: pagination.limit,
            total: pagination.total,
            onChange: (p) => fetchProducts(p),
          }}
        />
      </div>

      <Drawer
        title={editingProduct ? 'Edit Product' : 'Create Product'}
        open={drawerOpen}
        destroyOnHidden
        mask={false}
        width={isMobile ? '100%' : 600}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        onClose={() => { setDrawerOpen(false); setEditingProduct(null); form.resetFields(); resetPickerState(); }}
        extra={
          <Space>
            <Button onClick={() => { setDrawerOpen(false); setEditingProduct(null); form.resetFields(); resetPickerState(); }}>
              Cancel
            </Button>
            <Button type="primary" onClick={handleSubmit}>
              {editingProduct ? 'Save' : 'Create'}
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical" initialValues={{ type: 'DIGITAL', isActive: true }}>
          <Form.Item name="title" label="Title" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="slug" label="Slug" rules={[{ required: true, pattern: /^[a-z0-9-]+$/, message: 'lowercase, numbers, dashes only' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item name="priceCAD" label="Price (CAD)" rules={[{ required: true }]}>
            <InputNumber min={0} step={0.01} prefix="$" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="type" label="Type" rules={[{ required: true }]}>
            <Select options={[
              { value: 'DIGITAL', label: 'Digital Product' },
              { value: 'EVENT', label: 'Event Ticket' },
              { value: 'DONATION', label: 'Donation' },
            ]} />
          </Form.Item>

          {/* Image Source — gallery picker or external URL */}
          <Form.Item label="Product Image">
            {mediaEnabled && (
              <Radio.Group
                value={imageSource}
                onChange={(e) => setImageSource(e.target.value)}
                style={{ marginBottom: 12 }}
                optionType="button"
                buttonStyle="solid"
                size="small"
              >
                <Radio.Button value="gallery">From Gallery</Radio.Button>
                <Radio.Button value="url">External URL</Radio.Button>
              </Radio.Group>
            )}

            {imageSource === 'gallery' && mediaEnabled ? (
              <div>
                {selectedPhoto ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 4 }}>
                    <Image
                      src={selectedPhoto.thumbnailUrl}
                      alt="Selected photo"
                      width={80}
                      height={60}
                      style={{ objectFit: 'cover', borderRadius: 4 }}
                      preview={false}
                    />
                    <Space>
                      <Button size="small" onClick={() => setPhotoPickerOpen(true)}>Change</Button>
                      <Button
                        size="small"
                        danger
                        icon={<CloseCircleOutlined />}
                        onClick={() => setSelectedPhoto(null)}
                      />
                    </Space>
                  </div>
                ) : (
                  <Button
                    icon={<PictureOutlined />}
                    onClick={() => setPhotoPickerOpen(true)}
                    style={{ marginTop: 4 }}
                  >
                    Choose Photo
                  </Button>
                )}
              </div>
            ) : (
              <Form.Item name="imageUrl" noStyle>
                <Input placeholder="https://..." />
              </Form.Item>
            )}
          </Form.Item>

          {/* Promotional Video (media feature gated) */}
          {mediaEnabled && (
            <Form.Item label="Promotional Video">
              {selectedVideo ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag icon={<VideoCameraOutlined />} color="blue">{selectedVideo.title}</Tag>
                  <Button size="small" onClick={() => setVideoPickerOpen(true)}>Change</Button>
                  <Button
                    size="small"
                    danger
                    icon={<CloseCircleOutlined />}
                    onClick={() => setSelectedVideo(null)}
                  />
                </div>
              ) : (
                <Button icon={<VideoCameraOutlined />} onClick={() => setVideoPickerOpen(true)}>
                  Choose Video
                </Button>
              )}
            </Form.Item>
          )}

          {/* Gallery Photos (media feature gated) */}
          {mediaEnabled && (
            <Form.Item label="Gallery Photos">
              {galleryPhotos.length > 0 && (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
                  {galleryPhotos.map((photo) => (
                    <div key={photo.id} style={{ position: 'relative' }}>
                      <Image
                        src={photo.thumbnailUrl}
                        alt=""
                        width={64}
                        height={48}
                        style={{ objectFit: 'cover', borderRadius: 4 }}
                        preview={false}
                      />
                      <Button
                        size="small"
                        danger
                        icon={<CloseCircleOutlined />}
                        onClick={() => setGalleryPhotos((prev) => prev.filter((p) => p.id !== photo.id))}
                        style={{
                          position: 'absolute',
                          top: -6,
                          right: -6,
                          minWidth: 18,
                          width: 18,
                          height: 18,
                          padding: 0,
                          borderRadius: '50%',
                          fontSize: 10,
                        }}
                      />
                    </div>
                  ))}
                </div>
              )}
              <Button icon={<PictureOutlined />} onClick={() => setGalleryPickerOpen(true)}>
                Add Gallery Photos
              </Button>
            </Form.Item>
          )}

          <Form.Item name="downloadUrl" label="Download URL (for digital products)">
            <Input placeholder="File path or URL" />
          </Form.Item>
          <Form.Item name="maxPurchases" label="Max Purchases (capacity limit)">
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="isActive" label="Active" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Photo Picker for featured image */}
      <PhotoPickerModal
        open={photoPickerOpen}
        onClose={() => setPhotoPickerOpen(false)}
        onSelect={handlePhotoSelect}
        mode="single"
        title="Select Product Photo"
      />

      {/* Video Picker for promotional video */}
      <VideoPickerModal
        open={videoPickerOpen}
        onClose={() => setVideoPickerOpen(false)}
        onSelect={handleVideoSelect}
        mode="single"
        title="Select Promotional Video"
      />

      {/* Photo Picker for gallery photos (multiple) */}
      <PhotoPickerModal
        open={galleryPickerOpen}
        onClose={() => setGalleryPickerOpen(false)}
        onSelect={handleGalleryPhotoSelect}
        mode="multiple"
        title="Add Gallery Photos"
      />
    </>
  );
}
