'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Alert, Button, Form, Input, InputNumber, Modal, Select } from 'antd';
import { ApiError } from '../../lib/api';
import { accountsApi, notifyAccountsChanged, type AccountOption } from '../../lib/accounts';
import { contactsApi, type Contact } from '../../lib/contacts';
import { STAGE_META, dealsApi, notifyDealsChanged, type Deal, type DealInput, type DealStage } from '../../lib/deals';
import { notifyLeadsChanged, type DirectoryUser } from '../../lib/leads';
import { useCrmOptions } from '../../lib/options';

interface FormValues {
  title: string;
  accountId: string;
  contactId?: string;
  amount: number;
  stage: DealStage;
  closeDate?: string;
  engagementModel?: string;
  estimatedHours?: number;
  ownerId?: string;
}

function toDateInputValue(iso: string | null | undefined): string | undefined {
  if (!iso) return undefined;
  return iso.slice(0, 10);
}

export interface DealFormModalProps {
  open: boolean;
  deal: Deal | null;
  defaultStage?: DealStage;
  currentUserId: string;
  people: DirectoryUser[];
  onClose: () => void;
  onSaved: (saved: Deal) => void;
}

export function DealFormModal(props: DealFormModalProps) {
  if (!props.open) return null;
  return <DealFormModalInner {...props} />;
}

function DealFormModalInner({ open, deal, defaultStage, currentUserId, people, onClose, onSaved }: DealFormModalProps) {
  const [form] = Form.useForm<FormValues>();
  const { dealStages } = useCrmOptions();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [accountOptions, setAccountOptions] = useState<AccountOption[]>([]);
  const [contactsState, setContactsState] = useState<{
    accountId: string;
    items: Contact[];
  } | null>(null);
  const [accountsLoaded, setAccountsLoaded] = useState(false);

  const editing = Boolean(deal);
  const selectedAccountId = Form.useWatch('accountId', form);
  const accountContacts = selectedAccountId && contactsState?.accountId === selectedAccountId ? contactsState.items : [];
  const contactsLoading = open && Boolean(selectedAccountId) && contactsState?.accountId !== selectedAccountId;

  const initialValues = useMemo<Partial<FormValues>>(() => {
    if (deal) {
      return {
        title: deal.title,
        accountId: deal.accountId,
        contactId: deal.contactId ?? undefined,
        amount: deal.amount,
        stage: deal.stage,
        closeDate: toDateInputValue(deal.closeDate),
        engagementModel: deal.engagementModel ?? undefined,
        estimatedHours: deal.estimatedHours ?? undefined,
        ownerId: deal.owner?.id ?? currentUserId,
      };
    }
    return {
      title: '',
      amount: 0,
      stage: defaultStage ?? 'QUALIFICATION',
      ownerId: currentUserId,
    };
  }, [deal, defaultStage, currentUserId]);

  useEffect(() => {
    if (!open) return;
    let active = true;
    Promise.resolve().then(() => {
      if (active) setError(null);
    });

    accountsApi
      .options()
      .then((opts) => {
        if (active) setAccountOptions(opts);
      })
      .catch(() => {
        if (active) setAccountOptions([]);
      })
      .finally(() => {
        if (active) setAccountsLoaded(true);
      });

    return () => {
      active = false;
    };
  }, [open]);

  useEffect(() => {
    if (!open || !selectedAccountId) return;
    let active = true;
    contactsApi
      .list({
        view: 'all',
        accountId: selectedAccountId,
        pageSize: 100,
      })
      .then((page) => {
        if (active) {
          setContactsState({ accountId: selectedAccountId, items: page.items });
        }
      })
      .catch(() => {
        if (active) {
          setContactsState({ accountId: selectedAccountId, items: [] });
        }
      });
    return () => {
      active = false;
    };
  }, [open, selectedAccountId]);

  const submit = async (values: FormValues) => {
    setSaving(true);
    setError(null);
    const payload: DealInput = {
      title: values.title.trim(),
      accountId: values.accountId,
      contactId: values.contactId || null,
      amount: Number(values.amount ?? 0),
      stage: values.stage,
      closeDate: values.closeDate ? values.closeDate : null,
      engagementModel: values.engagementModel || null,
      estimatedHours: values.estimatedHours !== undefined && values.estimatedHours !== null ? Number(values.estimatedHours) : null,
      ownerId: values.ownerId || null,
    };

    try {
      const saved = deal ? await dealsApi.update(deal.id, payload) : await dealsApi.create(payload);
      notifyDealsChanged();
      notifyAccountsChanged();
      notifyLeadsChanged();
      onSaved(saved);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'This deal could not be saved. Try again.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      title={editing ? `Edit ${deal?.title ?? 'deal'}` : 'New deal'}
      onCancel={onClose}
      afterOpenChange={(visible) => {
        if (visible) form.setFieldsValue(initialValues);
      }}
      destroyOnHidden
      width={560}
      footer={
        <div className="flex justify-end gap-2">
          <Button type="text" onClick={onClose}>
            Cancel
          </Button>
          <Button type="primary" loading={saving} onClick={() => form.submit()}>
            {editing ? 'Save changes' : 'Create deal'}
          </Button>
        </div>
      }
    >
      {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}

      <Form key={deal?.id ?? 'new'} form={form} layout="vertical" initialValues={initialValues} onFinish={(v) => void submit(v)}>
        <div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
          <Form.Item
            name="title"
            label="Deal name"
            className="sm:col-span-2"
            rules={[
              { required: true, whitespace: true, message: 'Enter deal name' },
              { max: 255, message: 'Keep under 255 characters' },
            ]}
          >
            <Input placeholder="Enter deal title" autoFocus />
          </Form.Item>

          <Form.Item name="accountId" label="Customer" rules={[{ required: true, message: 'Choose a customer' }]}>
            <Select
              showSearch
              loading={open && !accountsLoaded}
              optionFilterProp="label"
              placeholder="Select a customer"
              onChange={() => form.setFieldValue('contactId', undefined)}
              options={accountOptions.map((a) => ({
                value: a.id,
                label: a.city ? `${a.name} (${a.city})` : a.name,
              }))}
            />
          </Form.Item>

          <Form.Item name="contactId" label="Primary contact">
            <Select
              allowClear
              showSearch
              disabled={!selectedAccountId}
              loading={contactsLoading}
              optionFilterProp="label"
              placeholder={selectedAccountId ? 'Select a contact (optional)' : 'Select a customer first'}
              notFoundContent="No contacts linked to this customer yet"
              options={accountContacts.map((c) => ({
                value: c.id,
                label: c.title ? `${c.name} · ${c.title}` : c.name,
              }))}
            />
          </Form.Item>

          <Form.Item name="amount" label="Deal value (INR)" rules={[{ required: true, message: 'Enter deal amount' }]}>
            <InputNumber className="!w-full" min={0} max={100000000000} step={50000} placeholder="500000" />
          </Form.Item>

          <Form.Item name="stage" label="Stage">
            <Select
              options={dealStages.map((st) => ({
                value: st.value,
                label: STAGE_META[st.value]?.label ?? st.label,
              }))}
            />
          </Form.Item>

          <Form.Item name="closeDate" label="Expected close date">
            <Input type="date" />
          </Form.Item>

          <Form.Item name="ownerId" label="Owner">
            <Select allowClear showSearch optionFilterProp="label" placeholder="Assign an owner" options={people.map((u) => ({ value: u.id, label: u.name }))} />
          </Form.Item>

          <Form.Item name="estimatedHours" label="Estimated effort (hours)">
            <InputNumber className="!w-full" min={0} max={100000} step={40} placeholder="480" />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}
