'use client';

import React, { useEffect, useState } from 'react';
import { Alert, Button, Form, Input, Modal, Select } from 'antd';
import { ApiError } from '../../lib/api';
import { dealsApi, notifyDealsChanged } from '../../lib/deals';
import { notifyAccountsChanged } from '../../lib/accounts';
import { notifyLeadsChanged } from '../../lib/leads';
import { useCrmOptions } from '../../lib/options';

interface LossFormValues {
  lossReason?: string;
  competitor?: string;
  lostNotes?: string;
}

export interface DealLossModalProps {
  open: boolean;
  deal: { id: string; title: string } | null;
  onClose: () => void;
  onSaved: () => void;
}

/** Captures optional win/loss context when moving a deal to Closed lost. */
export function DealLossModal(props: DealLossModalProps) {
  if (!props.open) return null;
  return <DealLossModalInner {...props} />;
}

function DealLossModalInner({ open, deal, onClose, onSaved }: DealLossModalProps) {
  const [form] = Form.useForm<LossFormValues>();
  const { lossReasons } = useCrmOptions();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    let active = true;
    Promise.resolve().then(() => {
      if (active) setError(null);
    });
    return () => {
      active = false;
    };
  }, [open, deal?.id]);

  const submit = async (values: LossFormValues) => {
    if (!deal) return;
    setSaving(true);
    setError(null);
    try {
      await dealsApi.moveStage(deal.id, {
        stage: 'CLOSED_LOST',
        lossReason: values.lossReason || null,
        competitor: values.competitor?.trim() || null,
        lostNotes: values.lostNotes?.trim() || null,
      });
      notifyDealsChanged();
      notifyAccountsChanged();
      notifyLeadsChanged();
      onSaved();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'This deal could not be marked as lost.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      title={deal ? `Mark "${deal.title}" as Closed lost` : 'Mark deal as lost'}
      onCancel={onClose}
      afterOpenChange={(visible) => {
        if (visible) form.resetFields();
      }}
      destroyOnHidden
      width={460}
      footer={
        <div className="flex justify-end gap-2">
          <Button type="text" onClick={onClose}>
            Cancel
          </Button>
          <Button type="primary" danger loading={saving} onClick={() => form.submit()}>
            Confirm Closed lost
          </Button>
        </div>
      }
    >
      {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}

      <p className="mb-4 mt-0 text-[13px] text-[var(--tcx-muted)]">Record why this opportunity did not close so your team can learn from lost deals.</p>

      <Form form={form} layout="vertical" onFinish={(v) => void submit(v)}>
        <Form.Item name="lossReason" label="Loss reason" rules={[{ required: true, message: 'Select why this deal was lost' }]}>
          <Select placeholder="Select primary reason" options={lossReasons.map((r) => ({ value: r, label: r }))} />
        </Form.Item>

        <Form.Item name="competitor" label="Competitor (if lost to another vendor)" rules={[{ max: 150, message: 'Keep under 150 characters' }]}>
          <Input placeholder="Enter competitor name" />
        </Form.Item>

        <Form.Item name="lostNotes" label="Notes" className="mb-0" rules={[{ max: 2000, message: 'Keep under 2000 characters' }]}>
          <Input.TextArea rows={3} placeholder="Optional context on pricing, timing or feedback" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
