"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Select, Textarea } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";

export default function EditSubscriptionPage() {
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const { user } = useAuth();
  const { language } = useLanguage();
  const isArabic = language === "ar";
  const id = params?.id;
  const canUpdate = !!user && hasPermission(user.role, "subscriptions:update");

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [amount, setAmount] = useState("0");
  const [currency, setCurrency] = useState("USD");
  const [billingCycle, setBillingCycle] = useState("monthly");
  const [status, setStatus] = useState("ACTIVE");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [nextBillingAt, setNextBillingAt] = useState("");

  useEffect(() => {
    if (!id) return;
    let cancel = false;
    setLoading(true);
    fetch(`/api/subscriptions/${id}`)
      .then((r) => r.json())
      .then((d) => {
        if (cancel) return;
        const row = d.data;
        setName(row?.name ?? "");
        setDescription(row?.description ?? "");
        setAmount(String(row?.amount ?? 0));
        setCurrency(row?.currency ?? "USD");
        setBillingCycle(row?.billingCycle ?? "monthly");
        setStatus(row?.status ?? "ACTIVE");
        setStartDate(row?.startDate ? String(row.startDate).slice(0, 10) : "");
        setEndDate(row?.endDate ? String(row.endDate).slice(0, 10) : "");
        setNextBillingAt(row?.nextBillingAt ? String(row.nextBillingAt).slice(0, 10) : "");
      })
      .catch(() => toast.error(isArabic ? "تعذر تحميل الاشتراك" : "Failed to load subscription"))
      .finally(() => !cancel && setLoading(false));
    return () => {
      cancel = true;
    };
  }, [id, isArabic]);

  const onSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!id) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/subscriptions/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          description: description || null,
          amount: Number(amount) || 0,
          currency,
          billingCycle,
          status,
          startDate: startDate || null,
          endDate: endDate || null,
          nextBillingAt: nextBillingAt || null,
        }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Failed");
      toast.success(isArabic ? "تم تحديث الاشتراك" : "Subscription updated");
      router.push("/subscriptions");
    } catch (err: any) {
      toast.error(err.message ?? (isArabic ? "تعذر التحديث" : "Failed to update"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <AppShell breadcrumbs={[{ label: isArabic ? "الاشتراكات" : "Subscriptions", href: "/subscriptions" }, { label: isArabic ? "تعديل" : "Edit" }]}>
      {!canUpdate ? (
        <Card>
          <CardContent className="py-10 text-center text-muted-foreground">
            {isArabic ? "ليس لديك صلاحية تعديل الاشتراكات." : "You do not have permission to edit subscriptions."}
          </CardContent>
        </Card>
      ) : (
      <form onSubmit={onSave} className="space-y-6">
        <Card>
          <CardHeader><CardTitle>{isArabic ? "تعديل الاشتراك" : "Edit Subscription"}</CardTitle></CardHeader>
          <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input label={isArabic ? "اسم الاشتراك" : "Subscription Name"} value={name} onChange={(e) => setName(e.target.value)} />
            <Select
              label={isArabic ? "الحالة" : "Status"}
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              options={[
                { value: "TRIAL", label: isArabic ? "تجريبي" : "Trial" },
                { value: "ACTIVE", label: isArabic ? "نشط" : "Active" },
                { value: "PAUSED", label: isArabic ? "موقوف" : "Paused" },
                { value: "CANCELLED", label: isArabic ? "ملغي" : "Cancelled" },
                { value: "EXPIRED", label: isArabic ? "منتهي" : "Expired" },
              ]}
            />
            <Input label={isArabic ? "المبلغ" : "Amount"} type="number" value={amount} onChange={(e) => setAmount(e.target.value)} />
            <Select
              label={isArabic ? "دورة الفوترة" : "Billing Cycle"}
              value={billingCycle}
              onChange={(e) => setBillingCycle(e.target.value)}
              options={[
                { value: "daily", label: isArabic ? "يومي" : "Daily" },
                { value: "weekly", label: isArabic ? "أسبوعي" : "Weekly" },
                { value: "monthly", label: isArabic ? "شهري" : "Monthly" },
                { value: "quarterly", label: isArabic ? "ربع سنوي" : "Quarterly" },
                { value: "yearly", label: isArabic ? "سنوي" : "Yearly" },
              ]}
            />
            <Select
              label={isArabic ? "العملة" : "Currency"}
              value={currency}
              onChange={(e) => setCurrency(e.target.value)}
              options={[
                { value: "USD", label: "USD" },
                { value: "EUR", label: "EUR" },
                { value: "GBP", label: "GBP" },
                { value: "SAR", label: "SAR" },
              ]}
            />
            <Input
              label={isArabic ? "تاريخ البداية" : "Start Date"}
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
            />
            <Input
              label={isArabic ? "تاريخ الانتهاء" : "End Date"}
              type="date"
              value={endDate}
              min={startDate || undefined}
              onChange={(e) => setEndDate(e.target.value)}
            />
            <Input
              label={isArabic ? "تاريخ الفاتورة القادمة" : "Next Billing Date"}
              type="date"
              value={nextBillingAt}
              min={startDate || undefined}
              onChange={(e) => setNextBillingAt(e.target.value)}
            />
            <div className="sm:col-span-2">
              <Textarea label={isArabic ? "الوصف" : "Description"} value={description} onChange={(e) => setDescription(e.target.value)} />
            </div>
          </CardContent>
        </Card>
        <div className="flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={() => router.back()} disabled={saving || loading}>{isArabic ? "إلغاء" : "Cancel"}</Button>
          <Button type="submit" loading={saving || loading}>{isArabic ? "حفظ" : "Save"}</Button>
        </div>
      </form>
      )}
    </AppShell>
  );
}
