'use client';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { canCreateLeadRequest } from '../access';
import { Alert, Button, Card, Col, InputNumber, Modal, notification, Row, Select, Space, Spin, Table, Typography } from 'antd';
import type { Dayjs } from 'dayjs';
import PageHeader from '@/components/pageHeader';
import DateRangePicker from '@/components/dateRangePicker';
import {
  addLeadRequests, countAvailableLeads, getCityOptions, getLaunchMembers, getLaunchOptions, getLaunchProjectOptions,
  getLocalityOptions, getProjectOptions, getSourceOptions,
} from '../service';
import {
  ROLE_LABELS, STATUS_GROUP_LABELS,
  type LaunchMember, type LeadFilters, type OptionItem, type StatusGroup,
} from '../interface';

const ALL = 'ALL';
const COUNT_DEBOUNCE_MS = 500;

const errorMessage = (error: any): string => {
  const message = error?.response?.data?.message;
  return Array.isArray(message) ? message.join(', ') : message ?? error?.message ?? 'Something went wrong';
};

// A multi-select with an "All" choice: picking All clears the rest, picking anything else drops All.
const withAll = (next: string[], previous: string[]): string[] => {
  if (next.includes(ALL) && !previous.includes(ALL)) return [ALL];
  return next.filter((v) => v !== ALL);
};

const Field: React.FC<{ label: string, children: React.ReactNode }> = ({ label, children }) => (
  <div>
    <Typography.Text strong style={{ display: 'block', marginBottom: 4 }}>{label}</Typography.Text>
    {children}
  </div>
);

const NewLeadRequestPage: React.FC = () => {
  const router = useRouter();
  const { data: session, status: sessionStatus } = useSession();
  const allowed = sessionStatus !== 'authenticated' || canCreateLeadRequest(session?.user);
  const userCityId: number | undefined = session?.user?.cities?.[0]?.city_id;

  // 1. Which leads
  const [cities, setCities] = useState<OptionItem[]>([]);
  const [sourceCity, setSourceCity] = useState<number>();
  const [localityOptions, setLocalityOptions] = useState<OptionItem[]>([]);
  const [localities, setLocalities] = useState<string[]>([]);
  const [projectOptions, setProjectOptions] = useState<OptionItem[]>([]);
  const [projects, setProjects] = useState<string[]>([]);
  const [statusGroup, setStatusGroup] = useState<StatusGroup>();
  const [sourceOptions, setSourceOptions] = useState<OptionItem[]>([]);
  const [sources, setSources] = useState<string[]>([]);
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);

  // 2. Where they go
  const [destCityChoice, setDestCityChoice] = useState<number>();
  const [launchOptions, setLaunchOptions] = useState<OptionItem[]>([]);
  const [destLaunch, setDestLaunch] = useState<number>();
  const [receivingOptions, setReceivingOptions] = useState<OptionItem[]>([]);
  const [receivingProject, setReceivingProject] = useState<number>();
  const [members, setMembers] = useState<LaunchMember[]>([]);
  const [routed, setRouted] = useState<Record<number, number>>({});

  const [quantity, setQuantity] = useState<number | null>(null);

  const [available, setAvailable] = useState<number | null>(null);
  const [counting, setCounting] = useState(false);
  const [quantityError, setQuantityError] = useState<string>();
  const [saving, setSaving] = useState(false);
  const countController = useRef<AbortController | null>(null);

  // The destination city starts as the source city until the user picks another.
  const destCity = destCityChoice ?? sourceCity;
  const crossCity = !!sourceCity && !!destCity && sourceCity !== destCity;

  const filters = useMemo<(LeadFilters & { destination_launch_id: number | null }) | null>(() => {
    if (!sourceCity || !statusGroup) return null;
    if (!localities.length || !projects.length || !sources.length) return null;
    const isAll = (values: string[]): boolean => values.includes(ALL);
    return {
      source_city_id: sourceCity,
      all_localities: isAll(localities),
      locality_ids: isAll(localities) ? [] : localities.map(Number),
      all_projects: isAll(projects),
      project_ids: isAll(projects) ? [] : projects.map(Number),
      all_sources: isAll(sources),
      source_ids: isAll(sources) ? [] : sources.map(Number),
      status_group: statusGroup,
      date_from: dateRange?.[0] ? dateRange[0].format('YYYY-MM-DD') : null,
      date_to: dateRange?.[1] ? dateRange[1].format('YYYY-MM-DD') : null,
      destination_launch_id: destLaunch ?? null,
    };
  }, [sourceCity, statusGroup, localities, projects, sources, dateRange, destLaunch]);

  const showError = (e: any): void => {
    notification.error({ message: 'Error', description: errorMessage(e) });
  };

  useEffect(() => {
    getCityOptions().then(setCities).catch(showError);
    getSourceOptions().then(setSourceOptions).catch(showError);
  }, []);

  // The Super Admin and the City Head approve requests, they do not raise them.
  useEffect(() => {
    if (!allowed) router.replace('/lead-requests');
  }, [allowed, router]);

  // The city starts as the logged-in user's own city; they can still change it.
  useEffect(() => {
    if (userCityId) setSourceCity((current) => current ?? userCityId);
  }, [userCityId]);

  // City -> localities. Changing the city clears everything that depends on it.
  useEffect(() => {
    setLocalities([]); setProjects([]); setLocalityOptions([]); setProjectOptions([]);
    if (sourceCity) getLocalityOptions(sourceCity).then(setLocalityOptions).catch(showError);
  }, [sourceCity]);

  // Localities -> projects.
  useEffect(() => {
    setProjects([]);
    if (!sourceCity) return;
    const chosen = localities.includes(ALL) ? [] : localities.map(Number);
    getProjectOptions(sourceCity, chosen).then(setProjectOptions).catch(showError);
  }, [sourceCity, localities]);

  // Destination city -> launches.
  useEffect(() => {
    setDestLaunch(undefined); setLaunchOptions([]);
    if (destCity) getLaunchOptions(destCity).then(setLaunchOptions).catch(showError);
  }, [destCity]);

  // Destination launch -> its members and receiving-project choices.
  useEffect(() => {
    setMembers([]); setRouted({}); setReceivingProject(undefined); setReceivingOptions([]);
    if (!destLaunch) return;
    getLaunchMembers(destLaunch).then(setMembers).catch(showError);
    getLaunchProjectOptions(destLaunch).then(setReceivingOptions).catch(showError);
  }, [destLaunch]);

  // Live available count: debounced, and an older call is cancelled so a stale answer never overwrites a newer one.
  useEffect(() => {
    countController.current?.abort();
    if (!filters) { setAvailable(null); setCounting(false); return undefined; }
    setCounting(true);
    const controller = new AbortController();
    countController.current = controller;
    const timer = setTimeout(() => {
      countAvailableLeads(filters, controller.signal)
        .then((count) => { setAvailable(count); setCounting(false); })
        .catch((e) => {
          if (controller.signal.aborted || e?.code === 'ERR_CANCELED') return;
          setCounting(false);
          showError(e);
        });
    }, COUNT_DEBOUNCE_MS);
    return () => { clearTimeout(timer); controller.abort(); };
  }, [filters]);

  // A quantity above the new count gets an inline error and is capped.
  useEffect(() => {
    if (available === null) return;
    if (quantity !== null && quantity > available) {
      setQuantityError(`Only ${available} leads are available${destLaunch ? ' in this launch' : ''}.`);
      setQuantity(available > 0 ? available : null);
    } else {
      setQuantityError(undefined);
    }
  }, [available]); // eslint-disable-line react-hooks/exhaustive-deps

  const routedTotal = Object.values(routed).reduce((sum, n) => sum + (n || 0), 0);
  const canSave = !!filters && !!destLaunch && !!destCity && !!quantity && !counting && available !== null &&
    quantity <= available && routedTotal > 0 && routedTotal <= quantity && (!crossCity || !!receivingProject);

  const save = (): void => {
    if (!filters || !destLaunch || !destCity || !quantity) return;
    const { destination_launch_id: _ignored, ...leadFilters } = filters;
    setSaving(true);
    addLeadRequests({
      ...leadFilters,
      destination_city_id: destCity,
      destination_launch_id: destLaunch,
      receiving_project_id: crossCity ? receivingProject ?? null : null,
      requested_count: quantity,
      routing: members
        .filter((m) => (routed[m.user_id] || 0) > 0)
        .map((m) => ({ user_id: m.user_id, role: m.role, quantity: routed[m.user_id] })),
    })
      .then((response) => {
        notification.success({ message: 'Success', description: response.message });
        router.push('/lead-requests');
      })
      .catch(showError)
      .finally(() => setSaving(false));
  };

  // Asks for a last confirmation before the request is created.
  const confirmSave = (): void => {
    const cityName = (id?: number): string => cities.find((c) => c.id === id)?.name ?? '-';
    const launchName = launchOptions.find((l) => l.id === destLaunch)?.name ?? '-';
    const receivers = members.filter((m) => (routed[m.user_id] || 0) > 0);
    Modal.confirm({
      title: 'Add lead request?',
      okText: 'Yes, add request',
      cancelText: 'Cancel',
      content: (
        <div>
          <p>
            Request <strong>{quantity}</strong> leads from <strong>{cityName(sourceCity)}</strong> to{' '}
            <strong>{launchName}</strong> ({cityName(destCity)}), the first batch when it is approved, then every day at 10:30 AM:
          </p>
          <ul style={{ paddingLeft: 20, margin: 0 }}>
            {receivers.map((m) => (
              <li key={m.user_id}>{m.name} ({ROLE_LABELS[m.role]}): {routed[m.user_id]} per day</li>
            ))}
          </ul>
          <p style={{ marginTop: 8 }}>It will be sent for approval.</p>
        </div>
      ),
      onOk: save,
    });
  };

  if (!allowed) return null;

  const allOption = { value: ALL, label: 'All' };
  const cityOptions = cities.map((c) => ({ value: c.id, label: c.name }));

  return (
    <div>
      <PageHeader title="Add Lead Request" isBack={true} />
      <Row gutter={16}>
        <Col xs={24} lg={17}>
          <Card title="1. Which leads" style={{ marginBottom: 16 }}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Field label="City">
                    <Select
                      style={{ width: '100%' }} placeholder="City" showSearch optionFilterProp="label" disabled={!!userCityId}
                      value={sourceCity} onChange={setSourceCity} options={cityOptions} />
                  </Field>
                </Col>
                <Col xs={24} md={12}>
                  <Field label="Localities">
                    <Select
                      mode="multiple" style={{ width: '100%' }} placeholder="Localities" autoClearSearchValue={false} disabled={!sourceCity}
                      value={localities} maxTagCount="responsive" optionFilterProp="label" onChange={(v) => setLocalities((prev) => withAll(v, prev))}
                      options={[allOption, ...localityOptions.map((l) => ({ value: String(l.id), label: l.name }))]} />
                  </Field>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Field label="Projects">
                    <Select
                      mode="multiple" style={{ width: '100%' }} placeholder="Projects" autoClearSearchValue={false} disabled={!localities.length}
                      value={projects} maxTagCount="responsive" optionFilterProp="label" onChange={(v) => setProjects((prev) => withAll(v, prev))}
                      options={[allOption, ...projectOptions.map((p) => ({ value: String(p.id), label: p.name }))]} />
                  </Field>
                </Col>
                <Col xs={24} md={12}>
                  <Field label="Sources">
                    <Select
                      mode="multiple" style={{ width: '100%' }} placeholder="Sources" autoClearSearchValue={false} value={sources} maxTagCount="responsive" optionFilterProp="label"
                      onChange={(v) => setSources((prev) => withAll(v, prev))}
                      options={[allOption, ...sourceOptions.map((s) => ({ value: String(s.id), label: s.name }))]} />
                  </Field>
                </Col>
              </Row>
              <Select
                style={{ width: '100%' }} placeholder="Lead status" value={statusGroup} onChange={setStatusGroup}
                options={(Object.keys(STATUS_GROUP_LABELS) as StatusGroup[]).map((k) => ({ value: k, label: STATUS_GROUP_LABELS[k] }))} />
              <DateRangePicker block placeholder="Lead created between" value={dateRange} onChange={setDateRange} />
            </Space>
          </Card>

          <Card title="2. Where they go" style={{ marginBottom: 16 }}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Field label="Destination city">
                    <Select
                      style={{ width: '100%' }} placeholder="Destination city" showSearch optionFilterProp="label" disabled={!!userCityId}
                      value={destCity} onChange={(v) => setDestCityChoice(v)} options={cityOptions} />
                  </Field>
                </Col>
                <Col xs={24} md={12}>
                  <Field label="Destination launch">
                    <Select
                      style={{ width: '100%' }} placeholder="Destination launch" disabled={!destCity} showSearch optionFilterProp="label"
                      value={destLaunch} onChange={setDestLaunch} options={launchOptions.map((l) => ({ value: l.id, label: l.name }))} />
                  </Field>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Field label="Total quantity">
                    <InputNumber
                      min={1} max={available ?? undefined} value={quantity} placeholder="Total leads to transfer" style={{ width: '100%' }}
                      onChange={(v) => { setQuantity(v); setQuantityError(undefined); }} />
                  </Field>
                </Col>
              </Row>
              {quantityError && <Typography.Text type="danger">{quantityError}</Typography.Text>}
              {crossCity && (
                <Select
                  style={{ width: '100%' }} placeholder="Receiving project" disabled={!destLaunch} showSearch optionFilterProp="label"
                  value={receivingProject} onChange={setReceivingProject} options={receivingOptions.map((p) => ({ value: p.id, label: p.name }))} />
              )}
              {destLaunch && (
                <>
                  <Table
                    size="small" rowKey="user_id" pagination={false} dataSource={members}
                    columns={[
                      { title: 'Name', dataIndex: 'name' },
                      { title: 'Role', dataIndex: 'role', render: (r: LaunchMember['role']) => ROLE_LABELS[r] },
                      {
                        title: 'Per day',
                        width: 140,
                        render: (_: unknown, m: LaunchMember) => (
                          <InputNumber
                            min={0} max={quantity ?? 0} value={routed[m.user_id] ?? 0}
                            onChange={(v) => setRouted((prev) => ({ ...prev, [m.user_id]: v ?? 0 }))} />
                        ),
                      },
                    ]} />
                  <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Space>
                      <Button onClick={() => setRouted({})}>Clear</Button>
                    </Space>
                  </div>
                </>
              )}
              {crossCity && !receivingProject && <Typography.Text type="secondary">Pick a receiving project to continue.</Typography.Text>}
              <Typography.Text type={quantity && routedTotal > quantity ? 'danger' : undefined}>
                {routedTotal} per day
                {quantity && routedTotal > 0 ? ` · ${Math.ceil(quantity / routedTotal)} day(s) to transfer ${quantity}` : ''}
                {quantity && routedTotal > quantity ? ' · per-day total is more than the total quantity' : ''}
              </Typography.Text>
              <Space>
                <Button type="primary" disabled={!canSave} loading={saving} onClick={confirmSave}>Save</Button>
                <Button onClick={() => router.push('/lead-requests')}>Cancel</Button>
              </Space>
            </Space>
          </Card>
        </Col>

        <Col xs={24} lg={7}>
          <div style={{ position: 'sticky', top: 16 }}>
            <Card>
              <Typography.Text type="secondary">Available leads</Typography.Text>
              <div style={{ fontSize: 32, fontWeight: 600 }}>
                {counting ? <Spin /> : available === null ? '-' : available.toLocaleString()}
              </div>
              {destLaunch && <Typography.Text type="secondary">Excludes leads already in this launch</Typography.Text>}
              {available === 0 && !counting && <Alert style={{ marginTop: 12 }} type="warning" message="No leads match these filters." />}
            </Card>
          </div>
        </Col>
      </Row>
    </div>
  );
};

export default NewLeadRequestPage;
