"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/admin/Toast";
import { apiPost, apiPatch, FetchError } from "@/lib/client-api";
import type { PublicPlan } from "@/modules/pricing/pricing.service";

interface PlanFormProps {
  plan?: PublicPlan;
  isNew?: boolean;
}

interface FormState {
  name: string;
  slug: string;
  description: string;
  price: number;
  currency: string;
  billingPeriod: string;
  offerPrice: number | null;
  discountType: string | null;
  discountValue: number | null;
  offerLabel: string;
  featuresText: string;
  eventLimit: number | null;
  guestLimit: number | null;
  storageLimitMb: number | null;
  teamMemberLimit: number | null;
  customModuleLimit: number | null;
  pdfExport: boolean;
  advancedReports: boolean;
  prioritySupport: boolean;
  customBranding: boolean;
  apiAccess: boolean;
  status: string;
  displayOrder: number;
  isPopular: boolean;
}

const empty: FormState = {
  name: "",
  slug: "",
  description: "",
  price: 0,
  currency: "USD",
  billingPeriod: "monthly",
  offerPrice: null,
  discountType: null,
  discountValue: null,
  offerLabel: "",
  featuresText: "",
  eventLimit: null,
  guestLimit: null,
  storageLimitMb: null,
  teamMemberLimit: null,
  customModuleLimit: null,
  pdfExport: false,
  advancedReports: false,
  prioritySupport: false,
  customBranding: false,
  apiAccess: false,
  status: "active",
  displayOrder: 0,
  isPopular: false,
};

function fromPlan(p?: PublicPlan): FormState {
  if (!p) return empty;
  return {
    name: p.name,
    slug: p.slug,
    description: p.description,
    price: p.price,
    currency: p.currency,
    billingPeriod: p.billingPeriod,
    offerPrice: p.offerPrice,
    discountType: p.discountType,
    discountValue: p.discountValue,
    offerLabel: p.offerLabel,
    featuresText: p.features.join("\n"),
    eventLimit: p.limits.eventLimit,
    guestLimit: p.limits.guestLimit,
    storageLimitMb: p.limits.storageLimitMb,
    teamMemberLimit: p.limits.teamMemberLimit,
    customModuleLimit: p.limits.customModuleLimit,
    pdfExport: p.planFeatures.pdfExport,
    advancedReports: p.planFeatures.advancedReports,
    prioritySupport: p.planFeatures.prioritySupport,
    customBranding: p.planFeatures.customBranding,
    apiAccess: p.planFeatures.apiAccess,
    status: p.status,
    displayOrder: p.displayOrder,
    isPopular: p.isPopular,
  };
}

function buildPayload(s: FormState) {
  return {
    name: s.name,
    slug: s.slug,
    description: s.description,
    price: s.price,
    currency: s.currency,
    billingPeriod: s.billingPeriod,
    offerPrice: s.offerPrice,
    discountType: s.discountType,
    discountValue: s.discountValue,
    offerLabel: s.offerLabel,
    features: s.featuresText
      .split("\n")
      .map((f) => f.trim())
      .filter(Boolean),
    limits: {
      eventLimit: s.eventLimit,
      guestLimit: s.guestLimit,
      storageLimitMb: s.storageLimitMb,
      teamMemberLimit: s.teamMemberLimit,
      customModuleLimit: s.customModuleLimit,
    },
    planFeatures: {
      pdfExport: s.pdfExport,
      advancedReports: s.advancedReports,
      prioritySupport: s.prioritySupport,
      customBranding: s.customBranding,
      apiAccess: s.apiAccess,
    },
    status: s.status,
    displayOrder: s.displayOrder,
    isPopular: s.isPopular,
  };
}

export function PlanForm({ plan, isNew }: PlanFormProps) {
  const router = useRouter();
  const [state, setState] = useState<FormState>(fromPlan(plan));
  const [pending, setPending] = useState(false);
  const update = (patch: Partial<FormState>) =>
    setState((s) => ({ ...s, ...patch }));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!state.name.trim() || !state.slug.trim()) {
      toast("Name and slug are required.", "error");
      return;
    }
    try {
      setPending(true);
      if (isNew) {
        await apiPost("/api/admin/pricing", buildPayload(state));
        toast("Plan created.", "success");
      } else if (plan) {
        await apiPatch(`/api/admin/pricing/${plan.id}`, buildPayload(state));
        toast("Plan saved.", "success");
      }
      router.refresh();
    } catch (err) {
      toast(err instanceof FetchError ? err.message : "Failed to save plan.", "error");
    } finally {
      setPending(false);
    }
  };

  const toggleStatus = async () => {
    if (!plan) return;
    try {
      setPending(true);
      const next = plan.status === "active" ? "inactive" : "active";
      if (next === "active") {
        await apiPost(`/api/admin/pricing/${plan.id}/status`);
      } else {
        await fetch(`/api/admin/pricing/${plan.id}/status`, {
          method: "DELETE",
          credentials: "include",
        });
      }
      toast(`Plan ${next === "active" ? "activated" : "deactivated"}.`, "info");
      router.refresh();
    } catch (err) {
      toast(err instanceof Error ? err.message : "Action failed.", "error");
    } finally {
      setPending(false);
    }
  };

  return (
    <form onSubmit={submit} className="mt-3 space-y-3">
      <div className="grid gap-2 sm:grid-cols-2">
        <FormField label="Name">
          <input
            required
            value={state.name}
            onChange={(e) => update({ name: e.target.value })}
            className="input"
          />
        </FormField>
        <FormField label="Slug">
          <input
            required
            value={state.slug}
            onChange={(e) => update({ slug: e.target.value })}
            className="input"
          />
        </FormField>
        <FormField label="Price">
          <input
            type="number"
            step="0.01"
            min={0}
            value={state.price}
            onChange={(e) => update({ price: Number(e.target.value) })}
            className="input"
          />
        </FormField>
        <FormField label="Currency">
          <input
            value={state.currency}
            onChange={(e) => update({ currency: e.target.value.toUpperCase() })}
            className="input"
          />
        </FormField>
        <FormField label="Billing period">
          <select
            value={state.billingPeriod}
            onChange={(e) => update({ billingPeriod: e.target.value })}
            className="input"
          >
            <option value="monthly">Monthly</option>
            <option value="yearly">Yearly</option>
            <option value="lifetime">Lifetime</option>
          </select>
        </FormField>
        <FormField label="Status">
          <select
            value={state.status}
            onChange={(e) => update({ status: e.target.value })}
            className="input"
          >
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="archived">Archived</option>
          </select>
        </FormField>
        <FormField label="Offer price">
          <input
            type="number"
            step="0.01"
            min={0}
            value={state.offerPrice ?? ""}
            onChange={(e) =>
              update({ offerPrice: e.target.value === "" ? null : Number(e.target.value) })
            }
            className="input"
          />
        </FormField>
        <FormField label="Offer label">
          <input
            value={state.offerLabel}
            onChange={(e) => update({ offerLabel: e.target.value })}
            className="input"
          />
        </FormField>
        <FormField label="Display order">
          <input
            type="number"
            value={state.displayOrder}
            onChange={(e) => update({ displayOrder: Number(e.target.value) })}
            className="input"
          />
        </FormField>
        <FormField label="Mark as popular">
          <label className="flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-2 text-sm">
            <input
              type="checkbox"
              checked={state.isPopular}
              onChange={(e) => update({ isPopular: e.target.checked })}
            />
            <span>Highlight as popular plan</span>
          </label>
        </FormField>
      </div>
      <FormField label="Description">
        <textarea
          value={state.description}
          onChange={(e) => update({ description: e.target.value })}
          className="input"
          rows={2}
        />
      </FormField>
      <FormField label="Features (one per line)">
        <textarea
          value={state.featuresText}
          onChange={(e) => update({ featuresText: e.target.value })}
          className="input"
          rows={4}
        />
      </FormField>
      <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
        <FormField label="Event limit">
          <LimitInput value={state.eventLimit} onChange={(v) => update({ eventLimit: v })} />
        </FormField>
        <FormField label="Guest limit">
          <LimitInput value={state.guestLimit} onChange={(v) => update({ guestLimit: v })} />
        </FormField>
        <FormField label="Storage (MB)">
          <LimitInput
            value={state.storageLimitMb}
            onChange={(v) => update({ storageLimitMb: v })}
          />
        </FormField>
        <FormField label="Team members">
          <LimitInput
            value={state.teamMemberLimit}
            onChange={(v) => update({ teamMemberLimit: v })}
          />
        </FormField>
        <FormField label="Custom modules">
          <LimitInput
            value={state.customModuleLimit}
            onChange={(v) => update({ customModuleLimit: v })}
          />
        </FormField>
      </div>
      <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
        <Toggle label="PDF export" value={state.pdfExport} onChange={(v) => update({ pdfExport: v })} />
        <Toggle label="Advanced reports" value={state.advancedReports} onChange={(v) => update({ advancedReports: v })} />
        <Toggle label="Priority support" value={state.prioritySupport} onChange={(v) => update({ prioritySupport: v })} />
        <Toggle label="Custom branding" value={state.customBranding} onChange={(v) => update({ customBranding: v })} />
        <Toggle label="API access" value={state.apiAccess} onChange={(v) => update({ apiAccess: v })} />
      </div>
      <div className="flex flex-wrap gap-2">
        <Button type="submit" size="sm" isLoading={pending}>
          {isNew ? "Create plan" : "Save changes"}
        </Button>
        {!isNew && plan ? (
          <Button
            type="button"
            variant="secondary"
            size="sm"
            onClick={toggleStatus}
            isLoading={pending}
          >
            {plan.status === "active" ? "Deactivate" : "Activate"}
          </Button>
        ) : null}
      </div>
      <style jsx>{`
        :global(.input) {
          width: 100%;
          border-radius: 0.5rem;
          border: 1px solid var(--border);
          background: var(--surface);
          padding: 0.5rem 0.75rem;
          font-size: 0.875rem;
        }
        :global(.input:focus) {
          outline: none;
          border-color: var(--primary);
        }
      `}</style>
    </form>
  );
}

function LimitInput({
  value,
  onChange,
}: {
  value: number | null;
  onChange: (v: number | null) => void;
}) {
  return (
    <div className="flex items-center gap-2 rounded-lg border border-border bg-surface px-2 py-1.5">
      <input
        type="checkbox"
        checked={value === null}
        onChange={(e) => onChange(e.target.checked ? null : 1)}
      />
      <span className="text-xs">Unlimited</span>
      <input
        type="number"
        min={0}
        disabled={value === null}
        value={value ?? ""}
        onChange={(e) =>
          onChange(e.target.value === "" ? null : Number(e.target.value))
        }
        className="ml-auto w-20 rounded border border-border bg-surface px-2 py-1 text-sm disabled:opacity-40"
      />
    </div>
  );
}

function Toggle({
  label,
  value,
  onChange,
}: {
  label: string;
  value: boolean;
  onChange: (v: boolean) => void;
}) {
  return (
    <label className="flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-2 text-sm">
      <input
        type="checkbox"
        checked={value}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span>{label}</span>
    </label>
  );
}

function FormField({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <label className="mb-1 block text-xs font-medium text-muted">{label}</label>
      {children}
    </div>
  );
}