'use client';

import React, { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Alert, App, Button, Checkbox, Form, Input, InputNumber, Modal, Radio } from 'antd';
import { Icon } from '../ui/Icon';
import { ApiError } from '../../lib/api';
import { inr, leadsApi, notifyLeadsChanged, type ConvertLeadResult, type DirectoryUser, type Lead } from '../../lib/leads';
import { notifyDealsChanged } from '../../lib/deals';
import { customersApi, notifyCustomersChanged, type CustomerDuplicate as AccountDuplicate } from '../../lib/customers';
import { notifyContactsChanged } from '../../lib/contacts';
import { CUSTOMER_MODAL_WIDTH, CustomerFormFields, toCustomerInput, type CustomerFormValues } from '../customers/CustomerFormFields';

interface ConvertFormValues extends CustomerFormValues {
  createDeal: boolean;
  dealTitle?: string;
  dealAmount?: number | null;
}

function defaultDealTitle(company: string, lead: Lead): string {
  return lead.serviceInterest ? `${company} — ${lead.serviceInterest}` : `${company} — New deal`;
}

export interface LeadConvertModalProps {
  open: boolean;
  lead: Lead;
  onClose: () => void;
  onConverted: (result: ConvertLeadResult) => void;
}

/**
 * Converts a lead with the same form as New customer, pre-filled from the lead, so details can be checked and completed.
 * When a customer with the same name exists the user chooses to add this contact to it or create a separate customer;
 * an optional deal section creates the first deal in the same transaction.
 */
export function LeadConvertModal(props: LeadConvertModalProps) {
  if (!props.open) return null;
  return <LeadConvertModalInner {...props} />;
}

function LeadConvertModalInner({ open, lead, onClose, onConverted }: LeadConvertModalProps) {
  const router = useRouter();
  const { message } = App.useApp();
  const [form] = Form.useForm<ConvertFormValues>();
  const [people, setPeople] = useState<DirectoryUser[]>([]);
  const [match, setMatch] = useState<{ key: string; account: AccountDuplicate | null } | null>(null);
  const [linkExisting, setLinkExisting] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [convertedResult, setConvertedResult] = useState<ConvertLeadResult | null>(null);

  const companyName = lead.company?.trim() || lead.name;
  const nameValue = (Form.useWatch('name', form) ?? companyName).trim();
  const createDeal = Form.useWatch('createDeal', form) ?? true;
  const matchKey = open && nameValue.length >= 2 ? `${lead.id}|${nameValue.toLowerCase()}` : '';
  const existing = match && match.key === matchKey ? match.account : null;
  const linking = Boolean(existing && linkExisting);

  const initialValues = useMemo<ConvertFormValues>(
    () => ({
      name: companyName,
      contactPerson: lead.name,
      email: lead.email ?? '',
      contactTitle: lead.title ?? undefined,
      phone: lead.phone ?? undefined,
      city: lead.city ?? undefined,
      ownerId: lead.owner?.id ?? undefined,
      createDeal: true,
      dealTitle: defaultDealTitle(companyName, lead),
      dealAmount: lead.estimatedValue || 0,
    }),
    [companyName, lead],
  );

  useEffect(() => {
    let active = true;
    leadsApi
      .directory()
      .then((list) => {
        if (active) setPeople(list);
      })
      .catch(() => {
        if (active) setPeople([]);
      });
    return () => {
      active = false;
    };
  }, []);

  useEffect(() => {
    if (!matchKey) return;
    let active = true;
    const timer = setTimeout(() => {
      customersApi
        .checkDuplicate({ name: nameValue })
        .then((items) => {
          if (active) setMatch({ key: matchKey, account: items.find((a) => a.name.trim().toLowerCase() === nameValue.toLowerCase()) ?? null });
        })
        .catch(() => {
          if (active) setMatch({ key: matchKey, account: null });
        });
    }, 300);
    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [matchKey, nameValue]);

  const submit = async (v: ConvertFormValues) => {
    setSaving(true);
    setError(null);
    const customer = toCustomerInput({ ...initialValues, ...v, name: linking && existing ? existing.name : v.name });
    try {
      const result = await leadsApi.convert(lead.id, {
        customer,
        ...(linking && existing ? { accountId: existing.id } : { newAccount: true }),
        createDeal: v.createDeal,
        ...(v.createDeal ? { dealTitle: v.dealTitle?.trim() || defaultDealTitle(customer.name, lead), dealAmount: Number(v.dealAmount ?? 0) } : {}),
      });
      notifyLeadsChanged();
      notifyCustomersChanged();
      notifyContactsChanged();
      if (result.deal) notifyDealsChanged();
      const label = [result.account.name, result.account.customerNumber].filter(Boolean).join(' · ');
      message.success(`${result.reusedAccount ? 'Added to customer' : 'Customer created'}: ${label}${result.deal ? ` with deal ${result.deal.dealNumber}` : ''}`);
      setConvertedResult(result);
      onConverted(result);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'This lead could not be converted.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      title={convertedResult ? 'Lead Converted' : 'Convert lead to customer'}
      onCancel={() => {
        setConvertedResult(null);
        onClose();
      }}
      afterOpenChange={(isOpen) => {
        if (!isOpen) {
          setError(null);
          setConvertedResult(null);
        }
      }}
      destroyOnHidden
      width={CUSTOMER_MODAL_WIDTH}
      footer={
        convertedResult ? null : (
          <div className="flex justify-end gap-2">
            <Button type="text" onClick={onClose}>
              Cancel
            </Button>
            <Button type="primary" loading={saving} onClick={() => form.submit()}>
              {linking ? 'Add to customer' : 'Convert to customer'}
            </Button>
          </div>
        )
      }
    >
      {convertedResult ? (
        <div className="py-2">
          <div className="mb-4 flex items-center gap-3 rounded-xl border border-emerald-200/80 bg-emerald-50/80 p-4 dark:border-emerald-900/50 dark:bg-emerald-950/30">
            <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/60 dark:text-emerald-300">
              <Icon name="check" size={20} />
            </span>
            <div>
              <h4 className="font-semibold text-emerald-950 text-[15px] dark:text-emerald-100">Lead Converted Successfully!</h4>
              <p className="mt-0.5 text-xs text-emerald-700 dark:text-emerald-400">{convertedResult.reusedAccount ? 'Contact successfully added to the existing customer record.' : 'New customer account, contact, and sales deal created.'}</p>
            </div>
          </div>

          <div className="space-y-3 mb-6">
            <div className="flex items-center justify-between rounded-xl border border-slate-200 bg-white p-3.5 dark:border-slate-800 dark:bg-slate-900">
              <div className="flex items-center gap-3 min-w-0">
                <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-50 text-blue-600 dark:bg-blue-950/60 dark:text-blue-400">
                  <Icon name="accounts" size={16} />
                </span>
                <div className="min-w-0">
                  <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">Customer Account</div>
                  <div className="truncate font-semibold text-slate-800 text-sm dark:text-slate-100">
                    {convertedResult.account.name}
                    {convertedResult.account.customerNumber ? ` · ${convertedResult.account.customerNumber}` : ''}
                  </div>
                </div>
              </div>
              <Button
                size="small"
                onClick={() => {
                  setConvertedResult(null);
                  onClose();
                  router.push(`/app/customers/${convertedResult.account.id}`);
                }}
              >
                View Customer ➔
              </Button>
            </div>

            {convertedResult.deal && (
              <div className="flex items-center justify-between rounded-xl border border-slate-200 bg-white p-3.5 dark:border-slate-800 dark:bg-slate-900">
                <div className="flex items-center gap-3 min-w-0">
                  <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-emerald-50 text-emerald-600 dark:bg-emerald-950/60 dark:text-emerald-400">
                    <Icon name="deals" size={16} />
                  </span>
                  <div className="min-w-0">
                    <div className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">Sales Deal</div>
                    <div className="truncate font-semibold text-slate-800 text-sm dark:text-slate-100">
                      {convertedResult.deal.dealNumber ? `${convertedResult.deal.dealNumber} · ` : ''}
                      {convertedResult.deal.title}
                      {convertedResult.deal.amount ? ` (${inr(convertedResult.deal.amount)})` : ''}
                    </div>
                  </div>
                </div>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    setConvertedResult(null);
                    onClose();
                    router.push(`/app/deals/${convertedResult.deal!.id}`);
                  }}
                >
                  Open Deal ➔
                </Button>
              </div>
            )}
          </div>

          <div className="flex items-center justify-between border-t border-slate-100 pt-3 dark:border-slate-800">
            <span className="text-xs text-slate-400">Select where you want to go next:</span>
            <div className="flex items-center gap-2">
              <Button
                onClick={() => {
                  setConvertedResult(null);
                  onClose();
                }}
              >
                Stay on Leads
              </Button>
              {convertedResult.deal ? (
                <Button
                  type="primary"
                  onClick={() => {
                    setConvertedResult(null);
                    onClose();
                    router.push(`/app/deals/${convertedResult.deal!.id}`);
                  }}
                >
                  Go to Deal Pipeline
                </Button>
              ) : (
                <Button
                  type="primary"
                  onClick={() => {
                    setConvertedResult(null);
                    onClose();
                    router.push(`/app/customers/${convertedResult.account.id}`);
                  }}
                >
                  Go to Customer
                </Button>
              )}
            </div>
          </div>
        </div>
      ) : (
        <>
          {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}
          {existing ? (
            <Alert
              type="warning"
              showIcon
              className="mb-4"
              title={`A customer named "${existing.name}" already exists${existing.customerNumber ? ` (${existing.customerNumber})` : ''}`}
              description={
                <Radio.Group value={linkExisting} onChange={(e) => setLinkExisting(e.target.value)} className="mt-1 flex flex-col gap-1">
                  <Radio value={true}>Add this contact to the existing customer</Radio>
                  <Radio value={false}>Create a separate new customer</Radio>
                </Radio.Group>
              }
            />
          ) : null}

          <Form<ConvertFormValues> form={form} layout="vertical" initialValues={initialValues} onFinish={(v) => void submit(v)} preserve={false}>
            {linking ? (
              <Form.Item name="name" hidden>
                <Input />
              </Form.Item>
            ) : null}
            <CustomerFormFields people={people} hideCompany={linking}>
              <Form.Item name="createDeal" valuePropName="checked" className="sm:col-span-2">
                <Checkbox>Also create a deal in the sales pipeline</Checkbox>
              </Form.Item>
              {createDeal ? (
                <>
                  <Form.Item
                    name="dealTitle"
                    label="Deal title"
                    rules={[
                      { required: true, whitespace: true, message: 'Enter deal title' },
                      { max: 255, message: 'Use 255 characters or fewer' },
                    ]}
                  >
                    <Input placeholder="Enter deal title" />
                  </Form.Item>
                  <Form.Item name="dealAmount" label="Expected value (₹)">
                    <InputNumber className="w-full" min={0} max={100000000000} step={25000} precision={0} placeholder="Enter expected value" />
                  </Form.Item>
                </>
              ) : null}
            </CustomerFormFields>
          </Form>
        </>
      )}
    </Modal>
  );
}

/** Displays linked Customer and Deal once a Lead has been converted. */
export function LeadConvertedCard({ lead, onNavigate }: { lead: Lead; onNavigate?: () => void }) {
  if (lead.status !== 'CONVERTED' || (!lead.convertedAccount && !lead.convertedDeal)) {
    return null;
  }

  const customerName = lead.convertedAccount ? [lead.convertedAccount.name, lead.convertedAccount.customerNumber].filter(Boolean).join(' · ') : 'Customer';
  const customerId = lead.convertedAccount?.id;

  return (
    <div className="mb-4 rounded-xl border border-emerald-200 bg-emerald-50/60 p-4 text-[13px] dark:border-emerald-900/50 dark:bg-emerald-950/30">
      <div className="flex items-center gap-2 font-semibold text-emerald-900 dark:text-emerald-100">
        <Icon name="check" size={16} className="text-emerald-600 dark:text-emerald-400" />
        <span>This lead has been converted</span>
      </div>
      <div className="mt-2.5 flex flex-wrap items-center gap-3">
        {customerId ? (
          <Link href={`/app/customers/${customerId}`} className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-800 shadow-xs hover:border-blue-500 hover:text-blue-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-200" onClick={() => onNavigate?.()}>
            <Icon name="accounts" size={14} className="text-blue-600" />
            <span>
              Customer: <b>{customerName}</b>
            </span>
            <Icon name="arrowRight" size={12} className="text-slate-400" />
          </Link>
        ) : null}
        {lead.convertedDeal ? (
          <Link href={`/app/deals/${lead.convertedDeal.id}`} className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-800 shadow-xs hover:border-emerald-500 hover:text-emerald-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-200" onClick={() => onNavigate?.()}>
            <Icon name="deals" size={14} className="text-emerald-600" />
            <span>
              Deal: <b>{lead.convertedDeal.title}</b> ({inr(lead.convertedDeal.amount)})
            </span>
            <Icon name="arrowRight" size={12} className="text-slate-400" />
          </Link>
        ) : null}
      </div>
    </div>
  );
}
