import { useState, useEffect, useCallback } from 'react';
import {
  Table, Tag, Button, Space, Drawer, Form, Input, Select, DatePicker, Popconfirm,
  message, Typography, Tabs, Grid,
} from 'antd';
import {
  PlusOutlined, CheckOutlined, StarOutlined, InboxOutlined, EditOutlined,
  DeleteOutlined, UserOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

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

interface Spotlight {
  id: string;
  userId: string;
  status: 'NOMINATED' | 'APPROVED' | 'FEATURED' | 'ARCHIVED';
  headline: string | null;
  story: string | null;
  featuredMonth: string | null;
  createdAt: string;
  user: { id: string; name: string | null; email: string };
  nominatedBy?: { id: string; name: string | null } | null;
  approvedBy?: { id: string; name: string | null } | null;
}

interface UserOption {
  id: string;
  name: string | null;
  email: string;
}

const STATUS_COLORS: Record<string, string> = {
  NOMINATED: 'blue',
  APPROVED: 'green',
  FEATURED: 'gold',
  ARCHIVED: 'default',
};

export default function SpotlightAdminPage() {
  const [spotlights, setSpotlights] = useState<Spotlight[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0 });
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [nominateOpen, setNominateOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [featureOpen, setFeatureOpen] = useState(false);
  const [selectedSpotlight, setSelectedSpotlight] = useState<Spotlight | null>(null);
  const [users, setUsers] = useState<UserOption[]>([]);
  const [userSearch, setUserSearch] = useState('');
  const [featureMonth, setFeatureMonth] = useState<dayjs.Dayjs | null>(null);

  const [nominateForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const fetchSpotlights = useCallback(async (page = 1) => {
    try {
      setLoading(true);
      const params: Record<string, string | number> = { page, limit: pagination.limit };
      if (statusFilter !== 'all') params.status = statusFilter;
      const { data } = await api.get('/social/spotlight/admin', { params });
      setSpotlights(data.spotlights || []);
      setPagination((prev) => ({ ...prev, page, total: data.pagination?.total || 0 }));
    } catch {
      message.error('Failed to load spotlights');
    } finally {
      setLoading(false);
    }
  }, [statusFilter, pagination.limit]);

  const searchUsers = useCallback(async (search: string) => {
    if (search.length < 2) return;
    try {
      const { data } = await api.get('/users', { params: { search, limit: 20 } });
      setUsers(data.users || []);
    } catch {
      // Ignore
    }
  }, []);

  useEffect(() => {
    fetchSpotlights(1);
  }, [fetchSpotlights]);

  useEffect(() => {
    if (userSearch.length >= 2) {
      const timer = setTimeout(() => searchUsers(userSearch), 300);
      return () => clearTimeout(timer);
    }
  }, [userSearch, searchUsers]);

  const handleNominate = async (values: { userId: string; headline?: string; story?: string }) => {
    try {
      await api.post('/social/spotlight/admin/nominate', values);
      message.success('Volunteer nominated');
      setNominateOpen(false);
      nominateForm.resetFields();
      fetchSpotlights(1);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to nominate'));
    }
  };

  const handleApprove = async (id: string) => {
    try {
      await api.post(`/social/spotlight/admin/${id}/approve`);
      message.success('Spotlight approved');
      fetchSpotlights(pagination.page);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to approve'));
    }
  };

  const handleFeature = async () => {
    if (!selectedSpotlight || !featureMonth) return;
    try {
      const month = featureMonth.format('YYYY-MM');
      await api.post(`/social/spotlight/admin/${selectedSpotlight.id}/feature`, { month });
      message.success('Spotlight featured');
      setFeatureOpen(false);
      setFeatureMonth(null);
      fetchSpotlights(pagination.page);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to feature'));
    }
  };

  const handleArchive = async (id: string) => {
    try {
      await api.post(`/social/spotlight/admin/${id}/archive`);
      message.success('Spotlight archived');
      fetchSpotlights(pagination.page);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to archive'));
    }
  };

  const handleEdit = async (values: { headline?: string; story?: string }) => {
    if (!selectedSpotlight) return;
    try {
      await api.put(`/social/spotlight/admin/${selectedSpotlight.id}`, values);
      message.success('Spotlight updated');
      setEditOpen(false);
      fetchSpotlights(pagination.page);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to update'));
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/social/spotlight/admin/${id}`);
      message.success('Spotlight deleted');
      fetchSpotlights(pagination.page);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to delete'));
    }
  };

  const openEdit = (record: Spotlight) => {
    setSelectedSpotlight(record);
    editForm.setFieldsValue({ headline: record.headline, story: record.story });
    setEditOpen(true);
  };

  const openFeature = (record: Spotlight) => {
    setSelectedSpotlight(record);
    setFeatureMonth(null);
    setFeatureOpen(true);
  };

  const { md } = Grid.useBreakpoint();
  const isMobile = !md;
  const activeDrawerWidth = !isMobile
    ? (nominateOpen || editOpen || featureOpen ? 480 : 0)
    : 0;

  const columns: ColumnsType<Spotlight> = [
    {
      title: 'Volunteer',
      key: 'user',
      render: (_, r) => (
        <div>
          <Text strong>{r.user.name || r.user.email}</Text>
          {r.user.name && <br />}
          {r.user.name && <Text type="secondary" style={{ fontSize: 12 }}>{r.user.email}</Text>}
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => (
        <Tag color={STATUS_COLORS[status]}>{status}</Tag>
      ),
    },
    {
      title: 'Headline',
      dataIndex: 'headline',
      key: 'headline',
      ellipsis: true,
      render: (v: string | null) => v || <Text type="secondary">--</Text>,
    },
    {
      title: 'Month',
      dataIndex: 'featuredMonth',
      key: 'featuredMonth',
      width: 110,
      render: (v: string | null) =>
        v ? dayjs(v + '-01').format('MMM YYYY') : <Text type="secondary">--</Text>,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 110,
      render: (v: string) => dayjs(v).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small" wrap>
          {record.status === 'NOMINATED' && (
            <Button
              size="small"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => handleApprove(record.id)}
            >
              Approve
            </Button>
          )}
          {record.status === 'APPROVED' && (
            <Button
              size="small"
              icon={<StarOutlined />}
              style={{ color: '#d4a017', borderColor: '#d4a017' }}
              onClick={() => openFeature(record)}
            >
              Feature
            </Button>
          )}
          {record.status !== 'ARCHIVED' && (
            <Button
              size="small"
              icon={<InboxOutlined />}
              onClick={() => handleArchive(record.id)}
            >
              Archive
            </Button>
          )}
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)} />
          <Popconfirm
            title="Delete this spotlight?"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div
        style={{
          marginRight: isMobile ? 0 : activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Typography.Title level={4} style={{ margin: 0 }}>Volunteer Spotlight</Typography.Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setNominateOpen(true)}>
            Nominate
          </Button>
        </div>

        <Tabs
          activeKey={statusFilter}
          onChange={(key) => setStatusFilter(key)}
          items={[
            { key: 'all', label: 'All' },
            { key: 'NOMINATED', label: 'Nominated' },
            { key: 'APPROVED', label: 'Approved' },
            { key: 'FEATURED', label: 'Featured' },
            { key: 'ARCHIVED', label: 'Archived' },
          ]}
          style={{ marginBottom: 16 }}
        />

        <Table
          dataSource={spotlights}
          columns={columns}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.page,
            total: pagination.total,
            pageSize: pagination.limit,
            onChange: (page) => fetchSpotlights(page),
            showTotal: (total) => `${total} spotlights`,
          }}
          scroll={{ x: 800 }}
        />
      </div>

      {/* Nominate Drawer */}
      <Drawer
        title="Nominate Volunteer"
        open={nominateOpen}
        onClose={() => { setNominateOpen(false); nominateForm.resetFields(); }}
        placement="right"
        width={isMobile ? '100%' : 480}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button type="primary" onClick={() => nominateForm.submit()}>
            Nominate
          </Button>
        }
      >
        <Form form={nominateForm} layout="vertical" onFinish={handleNominate}>
          <Form.Item name="userId" label="Volunteer" rules={[{ required: true, message: 'Select a volunteer' }]}>
            <Select
              showSearch
              placeholder="Search by name or email"
              filterOption={false}
              onSearch={setUserSearch}
              suffixIcon={<UserOutlined />}
              options={users.map((u) => ({
                value: u.id,
                label: `${u.name || ''} (${u.email})`.trim(),
              }))}
            />
          </Form.Item>
          <Form.Item name="headline" label="Headline">
            <Input maxLength={200} placeholder="A short title for their spotlight" />
          </Form.Item>
          <Form.Item name="story" label="Story">
            <TextArea rows={4} maxLength={2000} placeholder="Tell us why this volunteer deserves recognition" showCount />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Edit Drawer */}
      <Drawer
        title="Edit Spotlight"
        open={editOpen}
        onClose={() => setEditOpen(false)}
        placement="right"
        width={isMobile ? '100%' : 480}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button type="primary" onClick={() => editForm.submit()}>
            Save
          </Button>
        }
      >
        <Form form={editForm} layout="vertical" onFinish={handleEdit}>
          <Form.Item name="headline" label="Headline">
            <Input maxLength={200} />
          </Form.Item>
          <Form.Item name="story" label="Story">
            <TextArea rows={4} maxLength={2000} showCount />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Feature Drawer */}
      <Drawer
        title="Feature Spotlight"
        open={featureOpen}
        onClose={() => setFeatureOpen(false)}
        placement="right"
        width={isMobile ? '100%' : 480}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button type="primary" disabled={!featureMonth} onClick={handleFeature}>
            Feature
          </Button>
        }
      >
        <Text>Select the month to feature this volunteer:</Text>
        <div style={{ marginTop: 12 }}>
          <DatePicker
            picker="month"
            value={featureMonth}
            onChange={setFeatureMonth}
            style={{ width: '100%' }}
          />
        </div>
      </Drawer>
    </>
  );
}
