import { useState, useEffect, useCallback } from 'react';
import {
  Table, Card, Input, Button, Space, Tag, Drawer, Form, Switch,
  InputNumber, Select, Popconfirm, Typography, App, Progress, Tooltip, Grid,
} from 'antd';
import {
  PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined,
  LinkOutlined, EyeOutlined, PictureOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { DonationPage, DonationPageStatus, PaginationMeta, AppOutletContext } from '@/types/api';
import PhotoPickerModal from '@/components/media/PhotoPickerModal';

const { Text } = Typography;
const { TextArea } = Input;

const statusColors: Record<DonationPageStatus, string> = {
  DRAFT: 'default',
  ACTIVE: 'green',
  PAUSED: 'orange',
  ARCHIVED: 'red',
};

export default function DonationPagesPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [pages, setPages] = useState<DonationPage[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<DonationPageStatus | undefined>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editing, setEditing] = useState<DonationPage | null>(null);
  const [saving, setSaving] = useState(false);
  const [photoPickerOpen, setPhotoPickerOpen] = useState(false);
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const fetchPages = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = { page, limit: 20 };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get('/payments/admin/donation-pages', { params });
      setPages(data.pages);
      setPagination(data.pagination);
    } catch {
      message.error('Failed to load donation pages');
    } finally {
      setLoading(false);
    }
  }, [search, statusFilter, message]);

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

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

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({
      status: 'DRAFT',
      suggestedAmountsStr: '10, 25, 50, 100',
      minimumAmountDollars: 5,
      thankYouMessage: 'Thank you for your support!',
      showDonorCount: true,
      showTotalRaised: false,
      highlightPage: false,
    });
    setDrawerOpen(true);
  };

  const openEdit = (page: DonationPage) => {
    setEditing(page);
    const amounts = (page.suggestedAmounts || []).map((a) => (a / 100).toString()).join(', ');
    form.setFieldsValue({
      title: page.title,
      description: page.description,
      status: page.status,
      suggestedAmountsStr: amounts,
      minimumAmountDollars: page.minimumAmount / 100,
      thankYouMessage: page.thankYouMessage,
      coverPhoto: page.coverPhoto,
      coverVideoId: page.coverVideoId,
      goalAmountDollars: page.goalAmount ? page.goalAmount / 100 : null,
      showDonorCount: page.showDonorCount,
      showTotalRaised: page.showTotalRaised,
      highlightPage: page.highlightPage,
    });
    setDrawerOpen(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const values = await form.validateFields();
      // Parse suggested amounts from comma-separated dollars to cents array
      const suggestedAmounts = values.suggestedAmountsStr
        ? values.suggestedAmountsStr
            .split(',')
            .map((s: string) => Math.round(parseFloat(s.trim()) * 100))
            .filter((n: number) => !isNaN(n) && n >= 100)
        : undefined;

      const payload = {
        title: values.title,
        description: values.description || null,
        status: values.status,
        suggestedAmounts,
        minimumAmount: values.minimumAmountDollars ? Math.round(values.minimumAmountDollars * 100) : 500,
        thankYouMessage: values.thankYouMessage || undefined,
        coverPhoto: values.coverPhoto || null,
        coverVideoId: values.coverVideoId || null,
        goalAmount: values.goalAmountDollars ? Math.round(values.goalAmountDollars * 100) : null,
        showDonorCount: values.showDonorCount ?? true,
        showTotalRaised: values.showTotalRaised ?? false,
        highlightPage: values.highlightPage ?? false,
      };

      if (editing) {
        await api.put(`/payments/admin/donation-pages/${editing.id}`, payload);
        message.success('Donation page updated');
      } else {
        await api.post('/payments/admin/donation-pages', payload);
        message.success('Donation page created');
      }
      setDrawerOpen(false);
      fetchPages(pagination.page);
    } catch {
      message.error('Failed to save donation page');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/payments/admin/donation-pages/${id}`);
      message.success('Donation page deleted');
      fetchPages(pagination.page);
    } catch {
      message.error('Failed to delete donation page');
    }
  };

  const columns = [
    {
      title: 'Title',
      key: 'title',
      render: (_: unknown, r: DonationPage) => (
        <div>
          <div style={{ fontWeight: 600 }}>{r.title}</div>
          <Text type="secondary" style={{ fontSize: 12 }}>/{r.slug}</Text>
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (s: DonationPageStatus) => <Tag color={statusColors[s]}>{s}</Tag>,
    },
    {
      title: 'Donations',
      key: 'donations',
      render: (_: unknown, r: DonationPage) => r._count?.orders ?? 0,
      responsive: ['md'] as ('md')[],
    },
    {
      title: 'Total Raised',
      key: 'totalRaised',
      render: (_: unknown, r: DonationPage) => (
        <Text strong>${((r.totalRaised || 0) / 100).toFixed(2)}</Text>
      ),
      responsive: ['md'] as ('md')[],
    },
    {
      title: 'Goal',
      key: 'goal',
      render: (_: unknown, r: DonationPage) => {
        if (!r.goalAmount) return <Text type="secondary">-</Text>;
        const pct = Math.min(100, Math.round(((r.totalRaised || 0) / r.goalAmount) * 100));
        return (
          <div style={{ minWidth: 100 }}>
            <Progress percent={pct} size="small" />
            <Text type="secondary" style={{ fontSize: 11 }}>
              ${((r.totalRaised || 0) / 100).toFixed(0)} / ${(r.goalAmount / 100).toFixed(0)}
            </Text>
          </div>
        );
      },
      responsive: ['lg'] as ('lg')[],
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (v: string) => new Date(v).toLocaleDateString(),
      responsive: ['lg'] as ('lg')[],
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, r: DonationPage) => (
        <Space size="small">
          <Tooltip title="Edit">
            <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(r)} />
          </Tooltip>
          {r.status === 'ACTIVE' && (
            <Tooltip title="View Public Page">
              <Button
                size="small"
                icon={<EyeOutlined />}
                onClick={() => window.open(`/donate/${r.slug}`, '_blank')}
              />
            </Tooltip>
          )}
          <Tooltip title="Copy Link">
            <Button
              size="small"
              icon={<LinkOutlined />}
              onClick={() => {
                navigator.clipboard.writeText(`${window.location.origin}/donate/${r.slug}`);
                message.success('Link copied');
              }}
            />
          </Tooltip>
          <Popconfirm title="Delete this donation page?" onConfirm={() => handleDelete(r.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const activeDrawerWidth = !isMobile && drawerOpen ? 640 : 0;

  return (
    <>
      <div
        style={{
          marginRight: activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
      <Card style={{ marginBottom: 16 }}>
        <Space wrap>
          <Input
            placeholder="Search pages..."
            prefix={<SearchOutlined />}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onPressEnter={() => fetchPages(1)}
            style={{ width: 250 }}
          />
          <Select
            placeholder="Status"
            allowClear
            value={statusFilter}
            onChange={(v) => setStatusFilter(v)}
            style={{ width: 140 }}
          >
            <Select.Option value="DRAFT">Draft</Select.Option>
            <Select.Option value="ACTIVE">Active</Select.Option>
            <Select.Option value="PAUSED">Paused</Select.Option>
            <Select.Option value="ARCHIVED">Archived</Select.Option>
          </Select>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            Create Donation Page
          </Button>
        </Space>
      </Card>

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

      </div>

      <Drawer
        title={editing ? 'Edit Donation Page' : 'Create Donation Page'}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={isMobile ? '100%' : 640}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button type="primary" onClick={handleSave} loading={saving}>
            {editing ? 'Update' : 'Create'}
          </Button>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Title is required' }]}>
            <Input maxLength={200} />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <TextArea rows={3} maxLength={5000} />
          </Form.Item>
          <Form.Item name="status" label="Status">
            <Select>
              <Select.Option value="DRAFT">Draft</Select.Option>
              <Select.Option value="ACTIVE">Active</Select.Option>
              <Select.Option value="PAUSED">Paused</Select.Option>
              <Select.Option value="ARCHIVED">Archived</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="suggestedAmountsStr"
            label="Suggested Amounts (dollars, comma-separated)"
            tooltip="e.g. 10, 25, 50, 100"
          >
            <Input placeholder="10, 25, 50, 100" />
          </Form.Item>
          <Form.Item name="minimumAmountDollars" label="Minimum Amount ($)">
            <InputNumber min={1} step={1} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="thankYouMessage" label="Thank You Message">
            <TextArea rows={2} maxLength={2000} />
          </Form.Item>
          <Form.Item name="coverPhoto" label="Cover Photo URL">
            <Input
              placeholder="https://..."
              addonAfter={
                <Button
                  type="link"
                  size="small"
                  icon={<PictureOutlined />}
                  onClick={() => setPhotoPickerOpen(true)}
                  style={{ padding: 0, height: 'auto' }}
                >
                  Choose
                </Button>
              }
            />
          </Form.Item>
          <Form.Item name="coverVideoId" label="Cover Video ID (optional)">
            <InputNumber min={1} style={{ width: '100%' }} placeholder="Video ID from Media Library" />
          </Form.Item>
          <Form.Item name="goalAmountDollars" label="Fundraising Goal ($, optional)">
            <InputNumber min={1} step={1} style={{ width: '100%' }} placeholder="Leave empty for no goal" />
          </Form.Item>
          <Form.Item name="showDonorCount" label="Show Donor Count" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item name="showTotalRaised" label="Show Total Raised" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item
            name="highlightPage"
            label="Highlight Page"
            valuePropName="checked"
            tooltip="Only one page can be highlighted at a time"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Drawer>

      <PhotoPickerModal
        open={photoPickerOpen}
        onClose={() => setPhotoPickerOpen(false)}
        onSelect={(photo) => {
          form.setFieldValue('coverPhoto', photo.thumbnailUrl || photo.originalFilename);
          setPhotoPickerOpen(false);
        }}
        title="Choose Cover Photo"
      />
    </>
  );
}
