"use client";

import { useCallback, useEffect, useState } from "react";
import { PageHeader } from "@/components/layout/PageHeader";
import { EmptyState } from "@/components/layout/EmptyState";
import { ErrorState } from "@/components/layout/ErrorState";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { apiFetch, errorMessageForUi } from "@/lib/api";
import { formatStripeSyncStatus, stripeSyncBadgeVariant } from "@/lib/billing";
import { Textarea } from "@/components/ui/textarea";

type Product = { id: string; code: string; name: string; isActive: boolean };

type Plan = {
  id: string;
  code: string;
  name: string;
  description?: string | null;
  features?: string[];
  priceCents: number;
  currency: string;
  billingInterval: "MONTHLY" | "YEARLY";
  isActive: boolean;
  vehicleLimit?: number | null;
  products?: Product[];
  stripe?: {
    stripeEnabled: boolean;
    stripeSyncStatus: string;
    stripeProductId: string | null;
    stripePriceId: string | null;
    stripeSyncError: string | null;
  };
};

type PlanForm = {
  code: string;
  name: string;
  description: string;
  featuresText: string;
  vehicleLimit: string;
  priceCents: string;
  billingInterval: "MONTHLY" | "YEARLY";
  isActive: boolean;
  productIds: string[];
};

const emptyForm = (): PlanForm => ({
  code: "",
  name: "",
  description: "",
  featuresText: "",
  vehicleLimit: "",
  priceCents: "99",
  billingInterval: "MONTHLY",
  isActive: true,
  productIds: [],
});

function parseFeaturesText(text: string): string[] {
  return text
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean);
}

function parseVehicleLimit(raw: string): number | null {
  const trimmed = raw.trim();
  if (!trimmed) return null;
  const n = Number(trimmed);
  if (!Number.isFinite(n) || n < 0) return null;
  return Math.floor(n);
}

export default function PlansPage() {
  const [plans, setPlans] = useState<Plan[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<PlanForm>(emptyForm());
  const [editingId, setEditingId] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [formError, setFormError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [p, prod] = await Promise.all([
        apiFetch<Plan[]>("/plans?includeInactive=true"),
        apiFetch<Product[]>("/products?includeInactive=true"),
      ]);
      setPlans(p);
      setProducts(prod);
    } catch (err) {
      setError(errorMessageForUi(err, "Failed to load plans"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  function startEdit(plan: Plan) {
    setEditingId(plan.id);
    setForm({
      code: plan.code,
      name: plan.name,
      description: plan.description || "",
      featuresText: (plan.features || []).join("\n"),
      vehicleLimit: plan.vehicleLimit == null ? "" : String(plan.vehicleLimit),
      priceCents: String(plan.priceCents / 100),
      billingInterval: plan.billingInterval,
      isActive: plan.isActive,
      productIds: (plan.products || []).map((x) => x.id),
    });
    setFormError(null);
  }

  function cancelEdit() {
    setEditingId(null);
    setForm(emptyForm());
    setFormError(null);
  }

  async function savePlan() {
    setFormError(null);
    const priceDollars = Number(form.priceCents);
    if (!form.name.trim()) {
      setFormError("Name is required");
      return;
    }
    if (!editingId && !form.code.trim()) {
      setFormError("Code is required");
      return;
    }
    if (Number.isNaN(priceDollars) || priceDollars < 0) {
      setFormError("Price must be a non-negative number");
      return;
    }
    if (form.vehicleLimit.trim()) {
      const limit = Number(form.vehicleLimit);
      if (!Number.isFinite(limit) || limit < 0 || !Number.isInteger(limit)) {
        setFormError("Vehicle limit must be a whole number ≥ 0, or leave blank for unlimited");
        return;
      }
    }

    const priceCents = Math.round(priceDollars * 100);
    const features = parseFeaturesText(form.featuresText);
    const vehicleLimit = parseVehicleLimit(form.vehicleLimit);
    setBusy("save");
    try {
      if (editingId) {
        await apiFetch(`/plans/${editingId}`, {
          method: "PATCH",
          body: JSON.stringify({
            name: form.name.trim(),
            description: form.description.trim() || null,
            features,
            vehicleLimit,
            priceCents,
            billingInterval: form.billingInterval,
            isActive: form.isActive,
            productIds: form.productIds,
          }),
        });
      } else {
        await apiFetch("/plans", {
          method: "POST",
          body: JSON.stringify({
            code: form.code.trim().toLowerCase(),
            name: form.name.trim(),
            description: form.description.trim() || undefined,
            features,
            vehicleLimit,
            priceCents,
            billingInterval: form.billingInterval,
            isActive: form.isActive,
            productIds: form.productIds,
          }),
        });
      }
      cancelEdit();
      await load();
    } catch (err) {
      const message = errorMessageForUi(err, "Save failed");
      if (message) setFormError(message);
    } finally {
      setBusy(null);
    }
  }

  async function syncStripe(planId: string) {
    setBusy(`sync-${planId}`);
    setError(null);
    try {
      await apiFetch(`/plans/${planId}/sync-stripe`, { method: "POST" });
      await load();
    } catch (err) {
      setError(errorMessageForUi(err, "Stripe sync failed"));
    } finally {
      setBusy(null);
    }
  }

  function toggleProduct(id: string) {
    setForm((prev) => ({
      ...prev,
      productIds: prev.productIds.includes(id)
        ? prev.productIds.filter((x) => x !== id)
        : [...prev.productIds, id],
    }));
  }

  return (
    <>
      <PageHeader
        title="Plans"
        description="Manage plans, product entitlements, and Stripe Product/Price sync (TEST MODE)."
      />

      {error ? <ErrorState message={error} /> : null}

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="text-base">{editingId ? "Edit plan" : "Create plan"}</CardTitle>
          <CardDescription>
            Stripe secrets are never shown. Sync creates/updates Stripe Product and Price from this plan.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-3 sm:grid-cols-2">
            {!editingId ? (
              <div className="grid gap-1.5">
                <Label htmlFor="plan-code">Code</Label>
                <Input
                  id="plan-code"
                  value={form.code}
                  onChange={(e) => setForm((p) => ({ ...p, code: e.target.value }))}
                  placeholder="professional"
                />
              </div>
            ) : null}
            <div className="grid gap-1.5">
              <Label htmlFor="plan-name">Name</Label>
              <Input
                id="plan-name"
                value={form.name}
                onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
                placeholder="Professional"
              />
            </div>
            <div className="grid gap-1.5 sm:col-span-2">
              <Label htmlFor="plan-desc">Description</Label>
              <Input
                id="plan-desc"
                value={form.description}
                onChange={(e) => setForm((p) => ({ ...p, description: e.target.value }))}
                placeholder="Weight monitoring for professional fleets"
              />
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="plan-price">Price (USD)</Label>
              <Input
                id="plan-price"
                type="number"
                min={0}
                step="0.01"
                value={form.priceCents}
                onChange={(e) => setForm((p) => ({ ...p, priceCents: e.target.value }))}
              />
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="plan-interval">Billing</Label>
              <Select
                value={form.billingInterval}
                onValueChange={(value) =>
                  setForm((p) => ({
                    ...p,
                    billingInterval: value as "MONTHLY" | "YEARLY",
                  }))
                }
              >
                <SelectTrigger id="plan-interval">
                  <SelectValue placeholder="Select billing" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="MONTHLY">Monthly</SelectItem>
                  <SelectItem value="YEARLY">Yearly</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="plan-vehicle-limit">Vehicle limit</Label>
              <Input
                id="plan-vehicle-limit"
                type="number"
                min={0}
                step={1}
                value={form.vehicleLimit}
                onChange={(e) => setForm((p) => ({ ...p, vehicleLimit: e.target.value }))}
                placeholder="Blank = unlimited"
              />
            </div>
            <div className="grid gap-1.5 sm:col-span-2">
              <Label htmlFor="plan-features">Pricing features</Label>
              <Textarea
                id="plan-features"
                className="min-h-[100px]"
                value={form.featuresText}
                onChange={(e) => setForm((p) => ({ ...p, featuresText: e.target.value }))}
                placeholder={"One feature per line, e.g.\nUp to 25 vehicles\nFleet dashboard\nEmail support"}
              />
              <p className="text-xs text-muted-foreground">
                Shown on the marketing pricing page. Separate from Included Add-ins (app access).
              </p>
            </div>
          </div>

          <div>
            <p className="mb-2 text-sm font-medium">Included Add-ins</p>
            <p className="mb-2 text-xs text-muted-foreground">
              Controls which products the plan unlocks after purchase (entitlements).
            </p>
            <div className="flex flex-wrap gap-2">
              {products.map((prod) => {
                const checked = form.productIds.includes(prod.id);
                return (
                  <Button
                    key={prod.id}
                    type="button"
                    size="sm"
                    variant={checked ? "default" : "outline"}
                    onClick={() => toggleProduct(prod.id)}
                  >
                    {checked ? "✓ " : ""}
                    {prod.name}
                  </Button>
                );
              })}
              {!products.length ? (
                <p className="text-sm text-muted-foreground">No products seeded yet.</p>
              ) : null}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Checkbox
              id="plan-active"
              checked={form.isActive}
              onCheckedChange={(checked) =>
                setForm((p) => ({ ...p, isActive: checked === true }))
              }
            />
            <Label htmlFor="plan-active" className="font-normal">
              Active (available for purchase / assignment)
            </Label>
          </div>

          {formError ? (
            <Alert variant="destructive">
              <AlertTitle>Could not save</AlertTitle>
              <AlertDescription>{formError}</AlertDescription>
            </Alert>
          ) : null}

          <div className="flex flex-wrap gap-2">
            <Button disabled={busy !== null} onClick={() => void savePlan()}>
              {busy === "save" ? "Saving…" : editingId ? "Update plan" : "Create plan"}
            </Button>
            {editingId ? (
              <Button variant="outline" disabled={busy !== null} onClick={cancelEdit}>
                Cancel
              </Button>
            ) : null}
          </div>
        </CardContent>
      </Card>

      {loading ? (
        <Skeleton className="h-48 w-full" />
      ) : !plans.length ? (
        <EmptyState title="No plans" description="Create a plan to get started." />
      ) : (
        <div className="overflow-hidden rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Plan</TableHead>
                <TableHead>Price</TableHead>
                <TableHead className="hidden md:table-cell">Limit</TableHead>
                <TableHead>Add-ins</TableHead>
                <TableHead className="hidden lg:table-cell">Features</TableHead>
                <TableHead>Stripe</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {plans.map((plan) => (
                <TableRow key={plan.id}>
                  <TableCell>
                    <div className="font-medium">{plan.name}</div>
                    <div className="text-xs text-muted-foreground">{plan.code}</div>
                    <div className="mt-1 flex gap-1">
                      <Badge variant={plan.isActive ? "secondary" : "outline"}>
                        {plan.isActive ? "Active" : "Inactive"}
                      </Badge>
                    </div>
                  </TableCell>
                  <TableCell>
                    ${(plan.priceCents / 100).toFixed(2)} /{" "}
                    {plan.billingInterval === "YEARLY" ? "year" : "month"}
                  </TableCell>
                  <TableCell className="hidden text-sm md:table-cell">
                    {plan.vehicleLimit == null ? "Unlimited" : plan.vehicleLimit}
                  </TableCell>
                  <TableCell className="text-sm">
                    {(plan.products || []).map((p) => p.name).join(", ") || "—"}
                  </TableCell>
                  <TableCell className="hidden text-sm text-muted-foreground lg:table-cell">
                    {(plan.features || []).length
                      ? `${plan.features!.length} listed`
                      : "—"}
                  </TableCell>
                  <TableCell>
                    <Badge variant={stripeSyncBadgeVariant(plan.stripe?.stripeSyncStatus)}>
                      {formatStripeSyncStatus(plan.stripe?.stripeSyncStatus)}
                    </Badge>
                    {plan.stripe?.stripeProductId ? (
                      <p className="mt-1 font-mono text-[11px] text-muted-foreground">
                        {plan.stripe.stripeProductId}
                      </p>
                    ) : null}
                    {plan.stripe?.stripePriceId ? (
                      <p className="font-mono text-[11px] text-muted-foreground">
                        {plan.stripe.stripePriceId}
                      </p>
                    ) : null}
                    {plan.stripe?.stripeSyncError ? (
                      <p className="mt-1 text-xs text-destructive">{plan.stripe.stripeSyncError}</p>
                    ) : null}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button size="sm" variant="outline" onClick={() => startEdit(plan)}>
                        Edit
                      </Button>
                      <Button
                        size="sm"
                        disabled={busy !== null || !plan.isActive}
                        onClick={() => void syncStripe(plan.id)}
                      >
                        {busy === `sync-${plan.id}` ? "Syncing…" : "Sync to Stripe"}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
    </>
  );
}
