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

export default function NewQuotePage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [products, setProducts] = useState<any[]>([]);
  const [contacts, setContacts] = useState<any[]>([]);
  const [accounts, setAccounts] = useState<any[]>([]);
  const [opportunities, setOpportunities] = useState<any[]>([]);

  const quoteSchemaResolved = useMemo(() => createQuoteSchema(t), [t]);

  const { register, handleSubmit, control, watch, setValue, formState: { errors } } = useForm<QuoteInput>({
    resolver: zodResolver(quoteSchemaResolved),
    defaultValues: {
      currency: "USD",
      discountPercent: 0,
      opportunityId: searchParams.get("opportunityId") ?? "",
      contactId: searchParams.get("contactId") ?? "",
      lineItems: [{ description: "", quantity: 1, unitPrice: 0, discount: 0, taxRate: 0, order: 0 }],
    },
  });

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

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

  // Recalculate totals
  const totals = watchedItems?.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 = totals.subtotal * (discountPercent / 100);
  const total = totals.subtotal - discountAmt + totals.tax;

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

  const onSubmit = async (data: QuoteInput) => {
    setIsLoading(true);
    try {
      const res = await fetch("/api/quotes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
      if (!res.ok) throw new Error((await res.json()).error ?? t("toast.failed"));
      const result = await res.json();
      toast.success(t("toast.quoteCreated"));
      router.push(`/quotes/${result.data.id}`);
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : t("toast.failed"));
    }
    finally { setIsLoading(false); }
  };

  const currency = watch("currency") ?? "USD";

  return (
    <AppShell breadcrumbs={[{ label: t("nav.quotes"), href: "/quotes" }, { label: t("quotes.new") }]}>
      <div className="w-full min-w-0">
        <div className="mb-6"><h1 className="text-xl font-bold">{t("quotes.formCreateTitle")}</h1></div>
        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Header */}
          <Card>
            <CardHeader><CardTitle>{t("quotes.quoteDetailsCard")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Select label={t("quotes.opportunity")} options={opportunities.map(o => ({ value: o.id, label: o.title }))} placeholder={t("quotes.noOpportunity")} {...register("opportunityId")} />
              <Select label={t("quotes.contact")} options={contacts.map(c => ({ value: c.id, label: `${c.firstName} ${c.lastName}` }))} placeholder={t("quotes.noContact")} {...register("contactId")} />
              <Select label={t("quotes.account")} options={accounts.map(a => ({ value: a.id, label: a.name }))} placeholder={t("quotes.noAccount")} {...register("accountId")} />
              <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" }]} {...register("currency")} />
              <Input label={t("quotes.validUntil")} type="date" {...register("validUntil")} />
              <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("quotes.lineItems")}</CardTitle>
              <Button type="button" variant="outline" size="sm" onClick={() => append({ description: "", quantity: 1, unitPrice: 0, discount: 0, taxRate: 0, order: fields.length })}>
                <Plus className="w-4 h-4" /> {t("quotes.addLineItem")}
              </Button>
            </CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border bg-muted/30">
                      <th className="px-4 py-2 text-left text-xs font-semibold text-muted-foreground">{t("quotes.colProductDesc")}</th>
                      <th className="px-4 py-2 text-right text-xs font-semibold text-muted-foreground w-20">{t("quotes.colQty")}</th>
                      <th className="px-4 py-2 text-right text-xs font-semibold text-muted-foreground w-28">{t("quotes.colUnitPrice")}</th>
                      <th className="px-4 py-2 text-right text-xs font-semibold text-muted-foreground w-20">{t("quotes.colDiscPct")}</th>
                      <th className="px-4 py-2 text-right text-xs font-semibold text-muted-foreground w-20">{t("quotes.colTaxPct")}</th>
                      <th className="px-4 py-2 text-right text-xs font-semibold text-muted-foreground w-28">{t("quotes.total")}</th>
                      <th className="px-4 py-2 w-10"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {fields.map((field, index) => {
                      const item = watchedItems?.[index];
                      const lineAmt = (item?.quantity || 0) * (item?.unitPrice || 0);
                      const afterDiscount = lineAmt * (1 - (item?.discount || 0) / 100);
                      const tax = afterDiscount * ((item?.taxRate || 0) / 100);
                      const lineTotal = afterDiscount + tax;
                      return (
                        <tr key={field.id} className="hover:bg-muted/20">
                          <td className="px-4 py-3">
                            <div className="space-y-1.5">
                              <select
                                className="w-full h-8 text-xs rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring"
                                onChange={(e) => handleProductSelect(index, e.target.value)}
                                defaultValue=""
                              >
                                <option value="">{t("quotes.selectProduct")}</option>
                                {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                              </select>
                              <input {...register(`lineItems.${index}.description`)} placeholder={t("quotes.descPlaceholder")}
                                className="w-full h-8 text-xs rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring" />
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <input type="number" min={0.01} step={0.01} {...register(`lineItems.${index}.quantity`, { valueAsNumber: true })}
                              className="w-full h-8 text-xs text-right rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring" />
                          </td>
                          <td className="px-4 py-3">
                            <input type="number" min={0} step={0.01} {...register(`lineItems.${index}.unitPrice`, { valueAsNumber: true })}
                              className="w-full h-8 text-xs text-right rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring" />
                          </td>
                          <td className="px-4 py-3">
                            <input type="number" min={0} max={100} {...register(`lineItems.${index}.discount`, { valueAsNumber: true })}
                              className="w-full h-8 text-xs text-right rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring" />
                          </td>
                          <td className="px-4 py-3">
                            <input type="number" min={0} max={100} {...register(`lineItems.${index}.taxRate`, { valueAsNumber: true })}
                              className="w-full h-8 text-xs text-right rounded border border-input bg-background px-2 focus:outline-none focus:ring-1 focus:ring-ring" />
                          </td>
                          <td className="px-4 py-3 text-right">
                            <span className="text-sm font-medium">{formatCurrency(lineTotal, currency)}</span>
                          </td>
                          <td className="px-4 py-3">
                            {fields.length > 1 && (
                              <button type="button" onClick={() => remove(index)} className="text-muted-foreground hover:text-destructive">
                                <Trash2 className="w-4 h-4" />
                              </button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {/* Totals */}
              <div className="border-t border-border p-6 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(totals.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(totals.tax, currency)}</span></div>
                  <div className="flex justify-between font-bold text-base border-t border-border pt-2">
                    <span>{t("quotes.total")}</span><span className="text-primary">{formatCurrency(total, currency)}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Notes */}
          <Card>
            <CardHeader><CardTitle>{t("quotes.notesTermsCard")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Textarea label={t("quotes.notesCustomer")} rows={3} {...register("notes")} />
              <Textarea label={t("quotes.termsLabel")} rows={3} {...register("termsConditions")} />
            </CardContent>
          </Card>

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