"use client";
// src/app/invoices/new/page.tsx
import { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm, useFieldArray, Controller } from "react-hook-form";
import { AppShell } from "@/components/layout/AppShell";
import { Input, Select, Textarea, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { toast } from "sonner";
import { Plus, Trash2 } from "lucide-react";
import { formatCurrency } from "@/lib/utils";
import { useLanguage } from "@/i18n/LanguageContext";

interface LineItem {
  description: string;
  quantity: number;
  unitPrice: number;
  discount: number;
  taxRate: number;
  productId?: string;
}

interface FormData {
  accountId?: string;
  contactId?: string;
  dueDate?: string;
  currency: string;
  discountPercent: number;
  notes?: string;
  lineItems: LineItem[];
}

export default function NewInvoicePage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [quotePrefillLoading, setQuotePrefillLoading] = useState(() => !!searchParams.get("quoteId"));
  const [accounts, setAccounts] = useState<any[]>([]);
  const [contacts, setContacts] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);

  const quoteIdFromUrl = searchParams.get("quoteId");

  const { register, handleSubmit, control, watch, setValue, reset } = useForm<FormData>({
    defaultValues: {
      currency: "USD",
      discountPercent: 0,
      accountId: searchParams.get("accountId") ?? "",
      lineItems: [{ description: "", quantity: 1, unitPrice: 0, discount: 0, taxRate: 0 }],
    },
  });

  const { fields, append, remove } = useFieldArray({ control, name: "lineItems" });
  const lineItems = watch("lineItems");
  const currency = watch("currency");
  const discountPercent = watch("discountPercent") ?? 0;

  useEffect(() => {
    Promise.all([
      fetch("/api/companies?pageSize=200").then(r => r.json()),
      fetch("/api/customers?pageSize=200").then(r => r.json()),
      fetch("/api/products?pageSize=200&activeOnly=true").then(r => r.json()),
    ]).then(([a, c, p]) => {
      setAccounts(a.data?.items ?? []);
      setContacts(c.data?.items ?? []);
      setProducts(p.data?.items ?? []);
    });
  }, []);

  useEffect(() => {
    if (!quoteIdFromUrl) return;
    let cancelled = false;
    setQuotePrefillLoading(true);
    (async () => {
      try {
        const res = await fetch(`/api/quotes/${quoteIdFromUrl}`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error ?? "Failed");
        const quote = json.data;
        if (cancelled) return;
        if (quote.invoice?.id) {
          toast.error(t("invoices.quoteAlreadyInvoiced"));
          router.replace(`/invoices/${quote.invoice.id}`);
          return;
        }
        const due = new Date();
        due.setDate(due.getDate() + 30);
        const mappedLines: LineItem[] = (quote.lineItems?.length ? quote.lineItems : []).map((li: any) => ({
          description: li.description,
          quantity: Number(li.quantity),
          unitPrice: Number(li.unitPrice),
          discount: Number(li.discount ?? 0),
          taxRate: Number(li.taxRate ?? 0),
          productId: li.productId ?? undefined,
        }));
        if (mappedLines.length === 0) {
          mappedLines.push({ description: "", quantity: 1, unitPrice: 0, discount: 0, taxRate: 0 });
        }
        reset({
          accountId: quote.accountId ?? "",
          contactId: quote.contactId ?? "",
          currency: quote.currency ?? "USD",
          discountPercent: Number(quote.discountPercent ?? 0),
          dueDate: due.toISOString().slice(0, 10),
          notes: quote.notes ?? "",
          lineItems: mappedLines,
        });
      } catch {
        toast.error(t("invoices.quotePrefillError"));
      } finally {
        if (!cancelled) setQuotePrefillLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [quoteIdFromUrl, reset, router, t]);

  const calcLineTotal = (item: LineItem) => {
    const sub = (item.quantity || 0) * (item.unitPrice || 0);
    const afterDisc = sub * (1 - (item.discount || 0) / 100);
    return afterDisc * (1 + (item.taxRate || 0) / 100);
  };

  const lineTotals = lineItems?.reduce((acc, item) => {
    const lineAmt = (item.quantity || 0) * (item.unitPrice || 0);
    const afterDiscount = lineAmt * (1 - (item.discount || 0) / 100);
    const tax = afterDiscount * ((item.taxRate || 0) / 100);
    acc.subtotal += afterDiscount;
    acc.tax += tax;
    return acc;
  }, { subtotal: 0, tax: 0 }) ?? { subtotal: 0, tax: 0 };

  const discountAmt = lineTotals.subtotal * (discountPercent / 100);
  const grandTotal = lineTotals.subtotal - discountAmt + lineTotals.tax;

  const handleProductSelect = (idx: number, productId: string) => {
    const product = products.find(p => p.id === productId);
    if (product) {
      setValue(`lineItems.${idx}.description`, product.name);
      setValue(`lineItems.${idx}.unitPrice`, Number(product.price));
      setValue(`lineItems.${idx}.taxRate`, Number(product.taxRate));
    }
  };

  const onSubmit = async (data: FormData) => {
    if (!data.lineItems.length) { toast.error(t("invoices.toastMinOneLine")); return; }
    setIsLoading(true);
    try {
      const res = await fetch("/api/invoices", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...data,
          quoteId: quoteIdFromUrl || undefined,
          lineItems: data.lineItems.map((li, i) => ({ ...li, order: i })),
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      const result = await res.json();
      toast.success(t("invoices.toastCreated"));
      router.push(`/invoices/${result.data.id}`);
    } catch (e: any) { toast.error(e.message); }
    finally { setIsLoading(false); }
  };

  return (
    <AppShell breadcrumbs={[{ label: t("nav.invoices"), href: "/invoices" }, { label: t("invoices.newBreadcrumb") }]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("invoices.createPageTitle")}</h1>
          <p className="text-sm text-muted-foreground mt-0.5">{t("invoices.createPageSubtitle")}</p>
        </div>

        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Header */}
          <Card>
            <CardHeader><CardTitle>{t("invoices.detailsCard")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Controller
                name="accountId"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("quotes.account")}
                    options={accounts.map(a => ({ value: a.id, label: a.name }))}
                    placeholder={t("invoices.selectAccount")}
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Controller
                name="contactId"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("quotes.contact")}
                    options={contacts.map(c => ({ value: c.id, label: `${c.firstName} ${c.lastName}` }))}
                    placeholder={t("invoices.selectContact")}
                    value={field.value ?? ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Input label={t("invoices.dueDate")} type="date" {...register("dueDate")} />
              <Controller
                name="currency"
                control={control}
                render={({ field }) => (
                  <Select
                    label={t("common.currency")}
                    options={[
                      { value: "USD", label: "USD" }, { value: "EUR", label: "EUR" },
                      { value: "GBP", label: "GBP" }, { value: "SAR", label: "SAR" },
                      { value: "AED", label: "AED" },
                    ]}
                    value={field.value ?? "USD"}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    name={field.name}
                    ref={field.ref}
                  />
                )}
              />
              <Input
                label={t("quotes.overallDiscount")}
                type="number"
                min={0}
                max={100}
                step={0.5}
                {...register("discountPercent", { valueAsNumber: true })}
              />
            </CardContent>
          </Card>

          {/* Line Items */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{t("invoices.lineItemsTitle")}</CardTitle>
              <Button
                type="button" variant="outline" size="sm"
                onClick={() => append({ description: "", quantity: 1, unitPrice: 0, discount: 0, taxRate: 0 })}
              >
                <Plus className="w-4 h-4" /> {t("invoices.addLineItem")}
              </Button>
            </CardHeader>
            <CardContent className="p-0">
              {/* Header row */}
              <div className="grid grid-cols-12 gap-2 px-6 py-2 bg-muted/30 border-b border-border text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                <div className="col-span-4">{t("invoices.colDescription")}</div>
                <div className="col-span-1 text-right">{t("quotes.colQty")}</div>
                <div className="col-span-2 text-right">{t("quotes.colUnitPrice")}</div>
                <div className="col-span-1 text-right">{t("quotes.colDiscPct")}</div>
                <div className="col-span-1 text-right">{t("quotes.colTaxPct")}</div>
                <div className="col-span-2 text-right">{t("quotes.total")}</div>
                <div className="col-span-1" />
              </div>

              {fields.map((field, idx) => (
                <div key={field.id} className="grid grid-cols-12 gap-2 px-6 py-3 border-b border-border items-center">
                  <div className="col-span-4 space-y-1">
                    <select
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 focus:outline-none focus:ring-1 focus:ring-ring"
                      {...register(`lineItems.${idx}.productId`, {
                        onChange: (e) => {
                          const v = (e.target as HTMLSelectElement).value;
                          if (v) handleProductSelect(idx, v);
                        },
                      })}
                    >
                      <option value="">{t("invoices.selectProduct")}</option>
                      {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                    </select>
                    <input
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 focus:outline-none focus:ring-1 focus:ring-ring"
                      placeholder={t("invoices.lineDescPlaceholder")}
                      {...register(`lineItems.${idx}.description`)}
                    />
                  </div>
                  <div className="col-span-1">
                    <input type="number" min="0.01" step="0.01"
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 text-right focus:outline-none focus:ring-1 focus:ring-ring"
                      {...register(`lineItems.${idx}.quantity`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className="col-span-2">
                    <input type="number" min="0" step="0.01"
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 text-right focus:outline-none focus:ring-1 focus:ring-ring"
                      {...register(`lineItems.${idx}.unitPrice`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className="col-span-1">
                    <input type="number" min="0" max="100" step="0.1"
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 text-right focus:outline-none focus:ring-1 focus:ring-ring"
                      {...register(`lineItems.${idx}.discount`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className="col-span-1">
                    <input type="number" min="0" max="100" step="0.1"
                      className="w-full h-8 rounded border border-input bg-background text-xs px-2 text-right focus:outline-none focus:ring-1 focus:ring-ring"
                      {...register(`lineItems.${idx}.taxRate`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className="col-span-2 text-right">
                    <span className="text-sm font-semibold">
                      {formatCurrency(calcLineTotal(lineItems[idx] ?? field), currency)}
                    </span>
                  </div>
                  <div className="col-span-1 flex justify-end">
                    {fields.length > 1 && (
                      <button type="button" onClick={() => remove(idx)}
                        className="p-1 text-muted-foreground hover:text-destructive transition-colors">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                </div>
              ))}

              {/* Totals */}
              <div className="px-6 py-4 flex justify-end">
                <div className="w-64 space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">{t("quotes.subtotal")}</span>
                    <span>{formatCurrency(lineTotals.subtotal, currency)}</span>
                  </div>
                  {discountPercent > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>{t("quotes.discount")} ({discountPercent}%)</span>
                      <span>-{formatCurrency(discountAmt, currency)}</span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">{t("quotes.tax")}</span>
                    <span>{formatCurrency(lineTotals.tax, currency)}</span>
                  </div>
                  <div className="flex justify-between font-bold border-t border-border pt-2">
                    <span>{t("quotes.total")}</span>
                    <span className="text-primary">{formatCurrency(grandTotal, currency)}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Notes */}
          <Card>
            <CardHeader><CardTitle>{t("invoices.notesCard")}</CardTitle></CardHeader>
            <CardContent>
              <Textarea placeholder={t("invoices.notesClientPlaceholder")} rows={3} {...register("notes")} />
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading || quotePrefillLoading}>{t("common.cancel")}</Button>
            <Button type="submit" loading={isLoading || quotePrefillLoading}>{t("invoices.createPageTitle")}</Button>
          </div>
        </form>
      </div>
    </AppShell>
  );
}
