'use client';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button, Card, Input, Modal, notification, Select, Switch, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { EditOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons';
import PageHeader from '@/components/pageHeader';
import useDebounce from '@/hooks/useDebounce';
import { getActiveCities, getConfiguredCampaigns, setRotationActive, setSmsRotationActive, type ActiveCity } from './service';
import { LEAD_SOURCE_OPTIONS } from './constant';
import type { ConfiguredCampaign } from './interface';

const { Text } = Typography;

const DEFAULT_PAGE_SIZE = 5;

// The SOURCE dropdown's option values ('facebook'/'google'/'sms') vs. what's
// actually stored on a rotation row (SOURCE.* in constant/constant.js:
// 'Facebook'/'Google'/'SMS') — three different capitalisations, so this maps
// all three explicitly rather than special-casing just one.
function toBackendSource(source?: string): string | undefined {
  if (source === 'facebook') return 'Facebook';
  if (source === 'google') return 'Google';
  if (source === 'sms') return 'SMS';
  return source;
}

const CampaignsListPage: React.FC = () => {
  const router = useRouter();
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 400);
  // No source pre-selected — the list shows every campaign with a saved
  // rotation across all sources by default, not just Facebook.
  const [source, setSource] = useState<string>();
  const [cityId, setCityId] = useState<number>();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const [cities, setCities] = useState<ActiveCity[]>([]);
  useEffect(() => {
    getActiveCities().then(setCities);
  }, []);

  const cityName = cities.find((c) => c.id === cityId)?.name;

  const [configuredCampaigns, setConfiguredCampaigns] = useState<ConfiguredCampaign[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  // City, source, and search are all applied server-side — any change
  // re-fetches from the API rather than filtering already-loaded rows.
  useEffect(() => {
    setLoading(true);
    getConfiguredCampaigns({
      page,
      pageSize,
      source: toBackendSource(source),
      city_id: cityId,
      search: debouncedSearch || undefined,
    })
      .then((res) => {
        setConfiguredCampaigns(res.data);
        setTotal(res.total);
      })
      .finally(() => setLoading(false));
  }, [page, pageSize, source, cityId, debouncedSearch]);

  const applyStatus = (record: ConfiguredCampaign, isActive: boolean): void => {
    // SMS has its own toggle endpoint (keyed on project_id, not a campaign_id)
    // — routing anything non-Google to Facebook's endpoint, as this used to,
    // would silently 404/no-op an SMS rotation's toggle.
    const statusCall = record.source.toLowerCase() === 'sms'
      ? setSmsRotationActive(record.campaign_id, isActive)
      : setRotationActive(record.source.toLowerCase() === 'google' ? 'google' : 'facebook', record.campaign_id, isActive);

    statusCall
      .then(() => {
        setConfiguredCampaigns((prev) => prev.map((c) => (c.campaign_id === record.campaign_id && c.source === record.source ? { ...c, is_active: isActive } : c)));
        notification.success({ message: isActive ? 'Rotation activated.' : 'Rotation inactivated.' });
      })
      .catch((error: any) => {
        notification.error({ message: 'Error', description: error?.response?.data?.message || 'Failed to update the rotation status.' });
      });
  };

  // Turning a rotation off stops new leads reaching it, so it asks first; turning it on doesn't.
  const handleStatusChange = (record: ConfiguredCampaign, isActive: boolean): void => {
    if (isActive) {
      applyStatus(record, true);
      return;
    }
    Modal.confirm({
      title: 'Inactivate this rotation?',
      content: `"${record.name}" will stop receiving new leads until it is activated again. Its sales team and settings are kept.`,
      okText: 'Inactivate',
      okButtonProps: { danger: true },
      cancelText: 'Cancel',
      onOk: () => applyStatus(record, false),
    });
  };

  const goToEdit = (record: ConfiguredCampaign): void => {
    router.push(`/lead-routing/edit/${record.campaign_id}?cityId=${record.city_id}&source=${encodeURIComponent(record.source)}`);
  };

  const goToView = (record: ConfiguredCampaign): void => {
    router.push(`/lead-routing/view/${record.campaign_id}?cityId=${record.city_id}&source=${encodeURIComponent(record.source)}`);
  };

  const columns: ColumnsType<ConfiguredCampaign> = [
    {
      title: 'Campaign Name',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record) => (
        <div>
          <Typography.Text strong>{name}</Typography.Text>
          <div className="flex items-center gap-2 mt-1">
            <Tag color="blue" style={{ fontSize: 11 }}>{record.source}</Tag>
            <Text type="secondary" style={{ fontSize: 12 }}>{record.city_name}</Text>
          </div>
        </div>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      align: 'right',
      width: 170,
      render: (_, record) => (
        <div className="flex items-center justify-end gap-2">
          <Switch
            checked={record.is_active}
            checkedChildren="Active"
            unCheckedChildren="Inactive"
            onChange={(checked) => handleStatusChange(record, checked)}
          />
          <Button
            type="primary"
            shape="circle"
            icon={<EyeOutlined />}
            size="middle"
            title="View"
            onClick={() => goToView(record)}
          />
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            size="middle"
            title="Edit"
            onClick={() => goToEdit(record)}
          />
        </div>
      ),
    },
  ];

  return (
    <div>
      <PageHeader
        isBack={false}
        title="Rotations"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ background: '#16a34a', borderColor: '#16a34a' }}
            onClick={() => router.push('/lead-routing/add')}>
            Add Auto Gen
          </Button>
        }
      />

      <Card className="mb-3">
        <div className="flex flex-row items-start gap-6">
          <div className="flex-1">
            <Text type="secondary" style={{ fontSize: 11 }}>SEARCH</Text>
            <Input
              className="block mt-1"
              placeholder="Search campaign name..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
            />
          </div>
          <div style={{ width: 200, flexShrink: 0 }}>
            <Text type="secondary" style={{ fontSize: 11 }}>SOURCE</Text>
            <Select
              className="block mt-1"
              allowClear
              placeholder="All Sources"
              value={source}
              onChange={(value) => {
                setSource(value);
                setPage(1);
              }}
              options={LEAD_SOURCE_OPTIONS}
            />
          </div>
          <div style={{ width: 200, flexShrink: 0 }}>
            <Text type="secondary" style={{ fontSize: 11 }}>CITY</Text>
            <Select
              className="block mt-1"
              allowClear
              showSearch
              placeholder="All cities"
              value={cityId}
              filterOption={(input, option) => (option?.label as string).toLowerCase().includes(input.toLowerCase())}
              onChange={(value) => {
                setCityId(value);
                setPage(1);
              }}
              options={cities.map((c) => ({ value: c.id, label: c.name }))}
            />
          </div>
        </div>
      </Card>

      <Card
        title={
          <span style={{ fontSize: 13, color: '#888', fontWeight: 400 }}>
            CONFIGURED CAMPAIGNS — {cityName ? cityName.toUpperCase() : 'ALL CITIES'}
          </span>
        }
        extra={
          <Text type="secondary" style={{ fontSize: 12 }}>
            {total} total
          </Text>
        }>
        <Table<ConfiguredCampaign>
          rowKey="campaign_id"
          columns={columns}
          dataSource={configuredCampaigns}
          loading={loading}
          locale={{ emptyText: 'No Campaigns Found' }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '50'],
            showTotal: (t, range) => `${range[0]}-${range[1]} of ${t} entries`,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage);
              setPageSize(nextPageSize);
            },
          }}
        />
      </Card>
    </div>
  );
};

export default CampaignsListPage;
