'use client';

import React, { useEffect, useState } from 'react';
import { App, Button, DatePicker, Form, Input, InputNumber, Modal, Select } from 'antd';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { accountsApi, type AccountOption } from '../../lib/accounts';
import { dealsApi } from '../../lib/deals';
import { quotesApi, type QuoteRecord } from '../../lib/finance';
import { servicesApi, type ServiceRecord } from '../../lib/services';

function formatINR(val: number): string {
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(val);
}

export interface QuoteCreateModalProps {
  open: boolean;
  dealId?: string;
  accountId?: string;
  onClose: () => void;
  onSaved?: (quote: QuoteRecord) => void;
}

export function QuoteCreateModal({ open, dealId, accountId, onClose, onSaved }: QuoteCreateModalProps) {
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [accounts, setAccounts] = useState<AccountOption[]>([]);
  const [deals, setDeals] = useState<Array<{ id: string; title: string; accountId?: string | null }>>([]);
  const [services, setServices] = useState<ServiceRecord[]>([]);

  const [formItems, setFormItems] = useState<
    Array<{
      productId?: string;
      name: string;
      description?: string;
      quantity: number;
      unitPrice: number;
      discountPercent: number;
      gstRate: number;
    }>
  >([{ name: '', quantity: 1, unitPrice: 0, discountPercent: 0, gstRate: 18 }]);

  useEffect(() => {
    let active = true;
    if (!open) return;

    form.resetFields();
    form.setFieldsValue({
      accountId: accountId || undefined,
      dealId: dealId || undefined,
      expiryDate: dayjs().add(30, 'day'),
    });

    const loadOptions = async () => {
      await Promise.resolve();
      if (!active) return;
      setFormItems([{ name: '', quantity: 1, unitPrice: 0, discountPercent: 0, gstRate: 18 }]);
      try {
        const [accRes, dealsRes, srvRes] = await Promise.all([accountsApi.options(), dealsApi.list({ view: 'all', pageSize: 100 }), servicesApi.list({ activeOnly: true })]);
        if (!active) return;
        setAccounts(accRes || []);
        setDeals(dealsRes.items || []);
        setServices(srvRes || []);
      } catch {
        // non-critical error fallback
      }
    };
    void loadOptions();

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

  const handleAddBlankItem = () => {
    setFormItems((prev) => [...prev, { name: '', quantity: 1, unitPrice: 0, discountPercent: 0, gstRate: 18 }]);
  };

  const handleRemoveItem = (index: number) => {
    setFormItems((prev) => prev.filter((_, i) => i !== index));
  };

  const handleItemChange = (index: number, field: string, val: string | number) => {
    setFormItems((prev) => {
      const copy = [...prev];
      copy[index] = { ...copy[index], [field]: val };
      return copy;
    });
  };

  const liveTotals = formItems.reduce(
    (acc, it) => {
      const gross = it.quantity * it.unitPrice;
      const disc = gross * ((it.discountPercent || 0) / 100);
      const taxable = gross - disc;
      const tax = taxable * ((it.gstRate || 0) / 100);
      return {
        subtotal: acc.subtotal + gross,
        discount: acc.discount + disc,
        tax: acc.tax + tax,
        grand: acc.grand + taxable + tax,
      };
    },
    { subtotal: 0, discount: 0, tax: 0, grand: 0 },
  );

  const handleCreateSubmit = async () => {
    try {
      const values = await form.validateFields();
      const validItems = formItems.filter((it) => it.name.trim().length > 0 || it.unitPrice > 0);
      if (validItems.length === 0) {
        message.error('Please add at least one line item with a deliverable name and price');
        return;
      }

      setSubmitting(true);
      const newQuote = await quotesApi.create({
        accountId: values.accountId,
        dealId: values.dealId,
        serviceName: values.serviceName,
        quoteNumber: values.quoteNumber,
        expiryDate: values.expiryDate.toISOString(),
        notes: values.notes,
        terms: values.terms,
        items: validItems,
      });

      message.success('Quote proposal created successfully');
      onSaved?.(newQuote);
      onClose();
    } catch (err) {
      if (err instanceof Error && 'message' in err) {
        message.error(err.message);
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      title="Create New Quote Proposal"
      open={open}
      onOk={handleCreateSubmit}
      confirmLoading={submitting}
      onCancel={() => {
        if (!submitting) onClose();
      }}
      okText="Save Quote Proposal"
      width={780}
      destroyOnHidden
    >
      <Form form={form} layout="vertical" className="mt-4">
        {/* Top Header Information */}
        <div className="grid grid-cols-2 gap-4">
          <Form.Item name="accountId" label="Client Account" rules={[{ required: true, message: 'Select client account' }]}>
            <Select placeholder="Select client company" options={accounts.map((a) => ({ value: a.id, label: a.name }))} showSearch filterOption={(input, opt) => ((opt?.label as string) || '').toLowerCase().includes(input.toLowerCase())} />
          </Form.Item>

          <Form.Item name="serviceName" label="Services" rules={[{ required: true, message: 'Please select a service' }]}>
            <Select placeholder="Select required service..." options={services.map((s) => ({ value: s.name, label: s.name }))} showSearch filterOption={(input, opt) => ((opt?.label as string) || '').toLowerCase().includes(input.toLowerCase())} />
          </Form.Item>
        </div>

        <div className="grid grid-cols-3 gap-4">
          <Form.Item name="dealId" label="Linked Deal Opportunity">
            <Select placeholder="Select deal (Optional)" allowClear options={deals.map((d) => ({ value: d.id, label: d.title }))} showSearch filterOption={(input, opt) => ((opt?.label as string) || '').toLowerCase().includes(input.toLowerCase())} />
          </Form.Item>

          <Form.Item name="quoteNumber" label="Quote Number">
            <Input placeholder="Auto-generated sequence" />
          </Form.Item>

          <Form.Item name="expiryDate" label="Valid Until" rules={[{ required: true, message: 'Valid until date is required' }]}>
            <DatePicker className="w-full" format="DD MMM YYYY" />
          </Form.Item>
        </div>

        {/* Dynamic Line Items Section */}
        <div className="rounded-xl border border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] p-4">
          <div className="mb-3 flex items-center justify-between">
            <div>
              <span className="font-semibold text-[13.5px] text-[var(--tcx-text)]">Priced Deliverables & Line Items</span>
              <div className="text-[11.5px] text-[var(--tcx-muted)]">Item description and deliverable scope are manually typed.</div>
            </div>
            <Button size="small" type="primary" ghost icon={<Icon name="plus" size={13} />} onClick={handleAddBlankItem}>
              Add Deliverable
            </Button>
          </div>

          <div className="space-y-3">
            {formItems.map((item, idx) => (
              <div key={idx} className="flex items-start gap-2 rounded-lg border border-[var(--tcx-border)] bg-[var(--tcx-surface)] p-2.5 shadow-xs">
                <div className="flex-1">
                  <Input placeholder="Deliverable title" value={item.name} onChange={(e) => handleItemChange(idx, 'name', e.target.value)} className="mb-1 text-[13px] font-medium" />
                  <Input.TextArea autoSize={{ minRows: 1, maxRows: 3 }} placeholder="Enter scope and deliverable description" value={item.description} onChange={(e) => handleItemChange(idx, 'description', e.target.value)} className="text-[12px]" />
                </div>
                <div className="w-20">
                  <div className="mb-0.5 text-[11px] text-[var(--tcx-muted)]">Qty</div>
                  <InputNumber min={0.01} value={item.quantity} onChange={(v) => handleItemChange(idx, 'quantity', v || 1)} className="w-full" />
                </div>
                <div className="w-28">
                  <div className="mb-0.5 text-[11px] text-[var(--tcx-muted)]">Rate (₹)</div>
                  <InputNumber min={0} value={item.unitPrice} onChange={(v) => handleItemChange(idx, 'unitPrice', v || 0)} className="w-full" />
                </div>
                <div className="w-20">
                  <div className="mb-0.5 text-[11px] text-[var(--tcx-muted)]">Disc %</div>
                  <InputNumber min={0} max={100} value={item.discountPercent} onChange={(v) => handleItemChange(idx, 'discountPercent', v || 0)} className="w-full" />
                </div>
                <div className="w-28 text-right">
                  <div className="mb-0.5 text-[11px] text-[var(--tcx-muted)]">Line Total</div>
                  <div className="py-1 font-bold text-[13px] text-[var(--tcx-text)]">{formatINR(item.quantity * item.unitPrice * (1 - (item.discountPercent || 0) / 100) * 1.18)}</div>
                </div>
                {formItems.length > 1 && <Button size="small" type="text" danger icon={<Icon name="trash" size={14} />} onClick={() => handleRemoveItem(idx)} className="mt-5" aria-label="Remove item" />}
              </div>
            ))}
          </div>

          {/* Live Totals Bar */}
          <div className="mt-4 flex flex-col items-end border-t border-[var(--tcx-border)] pt-3 text-[13px]">
            <div className="flex w-64 justify-between py-0.5 text-[var(--tcx-muted)]">
              <span>Subtotal:</span>
              <span>{formatINR(liveTotals.subtotal)}</span>
            </div>
            <div className="flex w-64 justify-between py-0.5 text-[var(--tcx-muted)]">
              <span>Discount:</span>
              <span>− {formatINR(liveTotals.discount)}</span>
            </div>
            <div className="flex w-64 justify-between py-0.5 text-[var(--tcx-muted)]">
              <span>GST Tax (18%):</span>
              <span>{formatINR(liveTotals.tax)}</span>
            </div>
            <div className="mt-1 flex w-64 justify-between border-t border-[var(--tcx-border)] pt-1 text-[15px] font-bold text-[var(--tcx-text)]">
              <span>Grand Total:</span>
              <span className="text-[var(--tcx-primary)]">{formatINR(liveTotals.grand)}</span>
            </div>
          </div>
        </div>

        <div className="mt-4 grid grid-cols-2 gap-4">
          <Form.Item name="notes" label="Client Notes">
            <Input.TextArea rows={2} placeholder="Enter project scope and client notes" />
          </Form.Item>
          <Form.Item name="terms" label="Terms & Conditions">
            <Input.TextArea rows={2} placeholder="Enter payment terms and conditions" />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}
