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

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

export default function PlansPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [activeFilter, setActiveFilter] = useState<string | undefined>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editing, setEditing] = useState<SubscriptionPlan | 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 fetchPlans = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = { page, limit: 20 };
      if (search) params.search = search;
      if (activeFilter) params.isActive = activeFilter;
      const { data } = await api.get('/payments/admin/plans', { params });
      setPlans(data.plans);
      setPagination(data.pagination);
    } catch {
      message.error('Failed to load plans');
    } finally {
      setLoading(false);
    }
  }, [search, activeFilter, message]);

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

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

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({
      durationDays: 30,
      tier: 0,
      displayOrder: 0,
      isActive: true,
      highlightPlan: false,
      features: [],
    });
    setDrawerOpen(true);
  };

  const openEdit = (plan: SubscriptionPlan) => {
    setEditing(plan);
    form.setFieldsValue({
      name: plan.name,
      priceCAD: plan.priceCAD / 100,
      yearlyPriceCAD: plan.yearlyPriceCAD ? plan.yearlyPriceCAD / 100 : null,
      durationDays: plan.durationDays,
      description: plan.description,
      tier: plan.tier,
      displayOrder: plan.displayOrder,
      isActive: plan.isActive,
      features: (plan.features || []).map((f) => ({ value: f })),
      coverPhoto: plan.coverPhoto,
      coverVideoId: plan.coverVideoId,
      richDescription: plan.richDescription,
      ctaText: plan.ctaText,
      ctaSubtext: plan.ctaSubtext,
      highlightPlan: plan.highlightPlan,
    });
    setDrawerOpen(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const values = await form.validateFields();
      const payload = {
        name: values.name,
        priceCAD: Math.round(values.priceCAD * 100),
        yearlyPriceCAD: values.yearlyPriceCAD ? Math.round(values.yearlyPriceCAD * 100) : null,
        durationDays: values.durationDays,
        description: values.description || null,
        tier: values.tier ?? 0,
        displayOrder: values.displayOrder ?? 0,
        isActive: values.isActive ?? true,
        features: (values.features || []).map((f: { value: string }) => f.value).filter(Boolean),
        coverPhoto: values.coverPhoto || null,
        coverVideoId: values.coverVideoId || null,
        richDescription: values.richDescription || null,
        ctaText: values.ctaText || null,
        ctaSubtext: values.ctaSubtext || null,
        highlightPlan: values.highlightPlan ?? false,
      };

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

  const handleSync = async (id: number) => {
    try {
      await api.post(`/payments/admin/plans/${id}/sync-stripe`);
      message.success('Plan synced to Stripe');
      fetchPlans(pagination.page);
    } catch {
      message.error('Failed to sync to Stripe');
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/payments/admin/plans/${id}`);
      message.success('Plan deleted');
      fetchPlans(pagination.page);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to delete plan';
      message.error(msg);
    }
  };

  const columns = [
    {
      title: 'Name',
      key: 'name',
      render: (_: unknown, r: SubscriptionPlan) => (
        <div>
          <div style={{ fontWeight: 600 }}>
            {r.highlightPlan && <StarOutlined style={{ color: '#faad14', marginRight: 4 }} />}
            {r.name}
          </div>
          {r.slug && <Text type="secondary" style={{ fontSize: 12 }}>/{r.slug}</Text>}
        </div>
      ),
    },
    {
      title: 'Monthly',
      dataIndex: 'priceCAD',
      key: 'price',
      render: (v: number) => `$${(v / 100).toFixed(2)}/mo`,
    },
    {
      title: 'Yearly',
      dataIndex: 'yearlyPriceCAD',
      key: 'yearly',
      render: (v: number | null) => v ? `$${(v / 100).toFixed(2)}/yr` : '-',
      responsive: ['md'] as ('md')[],
    },
    {
      title: 'Tier',
      dataIndex: 'tier',
      key: 'tier',
      responsive: ['lg'] as ('lg')[],
    },
    {
      title: 'Active Subs',
      key: 'subs',
      render: (_: unknown, r: SubscriptionPlan) => r._count?.subscriptions ?? 0,
      responsive: ['md'] as ('md')[],
    },
    {
      title: 'Stripe',
      key: 'stripe',
      render: (_: unknown, r: SubscriptionPlan) => r.stripeProductId ? <Tag color="green">Synced</Tag> : <Tag>Not synced</Tag>,
      responsive: ['lg'] as ('lg')[],
    },
    {
      title: 'Active',
      dataIndex: 'isActive',
      key: 'active',
      render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? 'Yes' : 'No'}</Tag>,
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, r: SubscriptionPlan) => (
        <Space size="small">
          <Tooltip title="Edit">
            <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(r)} />
          </Tooltip>
          {r.slug && r.isActive && (
            <Tooltip title="View Public Page">
              <Button
                size="small"
                icon={<EyeOutlined />}
                onClick={() => window.open(`/pricing/${r.slug}`, '_blank')}
              />
            </Tooltip>
          )}
          {r.slug && (
            <Tooltip title="Copy Link">
              <Button
                size="small"
                icon={<LinkOutlined />}
                onClick={() => {
                  navigator.clipboard.writeText(`${window.location.origin}/pricing/${r.slug}`);
                  message.success('Link copied');
                }}
              />
            </Tooltip>
          )}
          <Tooltip title="Sync to Stripe">
            <Button size="small" icon={<SyncOutlined />} onClick={() => handleSync(r.id)} />
          </Tooltip>
          <Popconfirm title="Delete this plan?" 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 plans..."
            prefix={<SearchOutlined />}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onPressEnter={() => fetchPlans(1)}
            style={{ width: 250 }}
          />
          <Select
            placeholder="Status"
            allowClear
            value={activeFilter}
            onChange={(v) => setActiveFilter(v)}
            style={{ width: 140 }}
          >
            <Select.Option value="true">Active</Select.Option>
            <Select.Option value="false">Inactive</Select.Option>
          </Select>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            Create Plan
          </Button>
        </Space>
      </Card>

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

      </div>

      <Drawer
        title={editing ? 'Edit Plan' : 'Create Plan'}
        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">
          <Divider orientation="left" plain>Basic Info</Divider>
          <Form.Item name="name" label="Plan Name" rules={[{ required: true }]}>
            <Input maxLength={100} />
          </Form.Item>
          <Form.Item name="description" label="Short Description">
            <TextArea rows={2} maxLength={2000} placeholder="Brief description shown on pricing cards" />
          </Form.Item>
          <Form.Item name="priceCAD" label="Monthly Price (CAD)" rules={[{ required: true }]}>
            <InputNumber min={0} step={0.01} prefix="$" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="yearlyPriceCAD" label="Yearly Price (CAD, optional)">
            <InputNumber min={0} step={0.01} prefix="$" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="durationDays" label="Duration (days)" rules={[{ required: true }]}>
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>

          <Divider orientation="left" plain>Page Content</Divider>
          <Form.Item name="richDescription" label="Rich Description" tooltip="Detailed description shown on the individual plan page">
            <TextArea rows={4} maxLength={50000} placeholder="Detailed content for the plan's dedicated page..." />
          </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="ctaText" label="CTA Button Text" tooltip="Text on the subscribe button, e.g. 'Get Started'">
            <Input maxLength={200} placeholder="Subscribe Now" />
          </Form.Item>
          <Form.Item name="ctaSubtext" label="CTA Subtext" tooltip="Text below the CTA button">
            <Input maxLength={500} placeholder="Cancel anytime" />
          </Form.Item>

          <Divider orientation="left" plain>Features</Divider>
          <Form.List name="features">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Form.Item key={key} style={{ marginBottom: 8 }}>
                    <Space align="start" style={{ width: '100%' }}>
                      <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        noStyle
                        rules={[{ required: true, message: 'Feature text required' }]}
                      >
                        <Input placeholder="Feature description" style={{ width: isMobile ? 240 : 480 }} />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} style={{ color: '#ff4d4f', marginTop: 8 }} />
                    </Space>
                  </Form.Item>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    Add Feature
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>

          <Divider orientation="left" plain>Display</Divider>
          <Form.Item name="tier" label="Tier (0=free, 1=basic, 2=premium...)">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="displayOrder" label="Display Order">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="highlightPlan"
            label="Highlight Plan"
            valuePropName="checked"
            tooltip="Only one plan can be highlighted at a time. Highlighted plans appear first and get a special badge."
          >
            <Switch />
          </Form.Item>
          <Form.Item name="isActive" label="Active" valuePropName="checked">
            <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"
      />
    </>
  );
}
