"use client";

import { useState, useCallback } from "react";
import { Card, Badge, Button, ConfirmModal, Modal, Input, Toggle } from "@/shared/components";

const EMPTY_FORM = {
  name: "",
  description: "",
  rtpMinute: "",
  rtpDay: "",
  tokenLimitMonthly: "",
  creditLimit: "",
  creditToTokenRatio: "",
  maxConcurrent: "",
  durationDays: "",
  price: "",
  isActive: true,
};

export default function PackagesClient({ initialPackages = [] }) {
  const [packages, setPackages] = useState(initialPackages);
  const [error, setError] = useState("");
  const [confirmState, setConfirmState] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingPkg, setEditingPkg] = useState(null);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState("");

  const fetchPackages = useCallback(async () => {
    try {
      setError("");
      const res = await fetch("/api/packages");
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to fetch packages");
      }
      const data = await res.json();
      setPackages(data.packages || []);
    } catch (err) {
      setError(err.message || "An error occurred");
    }
  }, []);

  const openAddModal = () => {
    setEditingPkg(null);
    setForm(EMPTY_FORM);
    setFormError("");
    setModalOpen(true);
  };

  const openEditModal = (pkg) => {
    setEditingPkg(pkg);
    setForm({
      name: pkg.name || "",
      description: pkg.description || "",
      rtpMinute: pkg.rtpMinute ?? "",
      rtpDay: pkg.rtpDay ?? "",
      tokenLimitMonthly: pkg.tokenLimitMonthly ?? "",
      creditLimit: pkg.creditLimit ?? "",
      creditToTokenRatio: pkg.creditToTokenRatio ?? "",
      maxConcurrent: pkg.maxConcurrent ?? "",
      durationDays: pkg.durationDays ?? "",
      price: pkg.price ?? "",
      isActive: pkg.isActive !== false,
    });
    setFormError("");
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
    setEditingPkg(null);
    setForm(EMPTY_FORM);
    setFormError("");
  };

  const handleFormChange = (field, value) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const buildPayload = () => {
    const payload = {
      name: form.name.trim(),
      description: form.description.trim(),
      isActive: form.isActive,
    };
    const numericFields = [
      "rtpMinute",
      "rtpDay",
      "tokenLimitMonthly",
      "creditLimit",
      "creditToTokenRatio",
      "maxConcurrent",
      "durationDays",
      "price",
    ];
    for (const field of numericFields) {
      const val = form[field];
      if (val === "" || val === null || val === undefined) {
        payload[field] = undefined;
      } else {
        const num = Number(val);
        if (isNaN(num) || num < 0) {
          throw new Error(`${field} must be a non-negative number`);
        }
        payload[field] = num;
      }
    }
    return payload;
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      setFormError("");
      const payload = buildPayload();

      if (!payload.name) {
        setFormError("Name is required");
        setSaving(false);
        return;
      }

      const isEdit = !!editingPkg;
      const url = isEdit ? `/api/packages/${editingPkg.id}` : "/api/packages";
      const method = isEdit ? "PATCH" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || `Failed to ${isEdit ? "update" : "create"} package`);
      }

      closeModal();
      await fetchPackages();
    } catch (err) {
      setFormError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = (pkg) => {
    setConfirmState({
      title: "Delete Package",
      message: `Delete package "${pkg.name}"? This action cannot be undone.`,
      variant: "danger",
      onConfirm: async () => {
        setConfirmState(null);
        try {
          const res = await fetch(`/api/packages/${pkg.id}`, { method: "DELETE" });
          if (!res.ok) {
            const data = await res.json();
            if (res.status === 409 && data.assignedCount) {
              // Package assigned to users — ask for force delete
              setConfirmState({
                title: "Package In Use",
                message: `Package "${pkg.name}" is assigned to ${data.assignedCount} user(s). Deleting it will remove all user assignments. Continue?`,
                variant: "danger",
                confirmText: "Force Delete",
                onConfirm: async () => {
                  setConfirmState(null);
                  try {
                    const forceRes = await fetch(`/api/packages/${pkg.id}?force=true`, {
                      method: "DELETE",
                    });
                    if (!forceRes.ok) {
                      const forceData = await forceRes.json();
                      throw new Error(forceData.error || "Failed to delete package");
                    }
                    await fetchPackages();
                  } catch (err) {
                    setError(err.message);
                  }
                },
              });
              return;
            }
            throw new Error(data.error || "Failed to delete package");
          }
          await fetchPackages();
        } catch (err) {
          setError(err.message);
        }
      },
    });
  };

  const formatNumber = (n) => {
    if (n === null || n === undefined || n === "") return "—";
    return Number(n).toLocaleString();
  };

  if (error) {
    return (
      <div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="min-w-0">
            <h1 className="text-2xl font-semibold">Packages</h1>
            <p className="text-sm text-text-muted mt-1">Manage subscription packages and rate limits</p>
          </div>
        </div>
        <Card>
          <div className="text-center py-12">
            <p className="text-red-500 mb-4">{error}</p>
            <Button variant="outline" onClick={fetchPackages}>Retry</Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="min-w-0">
          <h1 className="text-2xl font-semibold">Packages</h1>
          <p className="text-sm text-text-muted mt-1">
            Manage subscription packages and rate limits
          </p>
        </div>
        <Button icon="add" onClick={openAddModal}>
          Add Package
        </Button>
      </div>

      {packages.length === 0 ? (
        <Card>
          <div className="text-center py-12">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
              <span className="material-symbols-outlined text-[32px]">inventory_2</span>
            </div>
            <p className="text-text-main font-medium mb-1">No packages yet</p>
            <p className="text-sm text-text-muted mb-4">
              Create your first package to get started
            </p>
            <Button icon="add" onClick={openAddModal}>Add Package</Button>
          </div>
        </Card>
      ) : (
        <div className="flex flex-col gap-4" data-testid="packages-list">
          {packages.map((pkg) => (
            <PackageRow
              key={pkg.id}
              pkg={pkg}
              onEdit={() => openEditModal(pkg)}
              onDelete={() => handleDelete(pkg)}
              formatNumber={formatNumber}
            />
          ))}
        </div>
      )}

      {/* Add / Edit Modal */}
      <Modal
        isOpen={modalOpen}
        onClose={closeModal}
        title={editingPkg ? "Edit Package" : "Add Package"}
        size="lg"
        footer={
          <>
            <Button variant="ghost" onClick={closeModal} disabled={saving}>
              Cancel
            </Button>
            <Button onClick={handleSave} loading={saving}>
              {editingPkg ? "Save Changes" : "Create Package"}
            </Button>
          </>
        }
      >
        <div className="flex flex-col gap-4">
          {formError && (
            <div className="p-3 rounded-[10px] bg-red-500/10 border border-red-500/20 text-red-500 text-sm">
              {formError}
            </div>
          )}

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Name"
              required
              placeholder="e.g. Pro"
              value={form.name}
              onChange={(e) => handleFormChange("name", e.target.value)}
            />
            <Input
              label="Price"
              type="number"
              placeholder="0"
              value={form.price}
              onChange={(e) => handleFormChange("price", e.target.value)}
              hint="In credits"
            />
          </div>

          <Input
            label="Description"
            placeholder="Short description of this package"
            value={form.description}
            onChange={(e) => handleFormChange("description", e.target.value)}
          />

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="RPM (Requests Per Minute)"
              type="number"
              placeholder="0"
              value={form.rtpMinute}
              onChange={(e) => handleFormChange("rtpMinute", e.target.value)}
            />
            <Input
              label="RPD (Requests Per Day)"
              type="number"
              placeholder="0"
              value={form.rtpDay}
              onChange={(e) => handleFormChange("rtpDay", e.target.value)}
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Monthly Token Limit"
              type="number"
              placeholder="0"
              value={form.tokenLimitMonthly}
              onChange={(e) => handleFormChange("tokenLimitMonthly", e.target.value)}
            />
            <Input
              label="Credit Limit"
              type="number"
              placeholder="0"
              value={form.creditLimit}
              onChange={(e) => handleFormChange("creditLimit", e.target.value)}
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <Input
              label="Credit to Token Ratio"
              type="number"
              placeholder="1000"
              value={form.creditToTokenRatio}
              onChange={(e) => handleFormChange("creditToTokenRatio", e.target.value)}
              hint="Tokens per credit"
            />
            <Input
              label="Max Concurrent"
              type="number"
              placeholder="0"
              value={form.maxConcurrent}
              onChange={(e) => handleFormChange("maxConcurrent", e.target.value)}
            />
            <Input
              label="Duration (Days)"
              type="number"
              placeholder="30"
              value={form.durationDays}
              onChange={(e) => handleFormChange("durationDays", e.target.value)}
            />
          </div>

          <Toggle
            label="Active"
            description="Inactive packages cannot be assigned to users"
            checked={form.isActive}
            onChange={(val) => handleFormChange("isActive", val)}
          />
        </div>
      </Modal>

      {/* Delete Confirmation */}
      <ConfirmModal
        isOpen={!!confirmState}
        onClose={() => setConfirmState(null)}
        onConfirm={confirmState?.onConfirm}
        title={confirmState?.title || "Confirm"}
        message={confirmState?.message}
        confirmText={confirmState?.confirmText || "Delete"}
        variant={confirmState?.variant || "danger"}
      />
    </div>
  );
}

function PackageRow({ pkg, onEdit, onDelete, formatNumber }) {
  const statusVariant = pkg.isActive !== false ? "success" : "default";
  const statusLabel = pkg.isActive !== false ? "Active" : "Inactive";

  return (
    <Card padding="sm" className="group">
      <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex min-w-0 flex-1 items-start gap-3">
          <div className="size-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
            <span className="material-symbols-outlined text-primary text-[18px]">inventory_2</span>
          </div>
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2 mb-1">
              <span className="font-medium text-sm text-text-main">{pkg.name}</span>
              <Badge variant={statusVariant} size="sm" dot>
                {statusLabel}
              </Badge>
              {pkg.price > 0 && (
                <Badge variant="primary" size="sm">
                  {formatNumber(pkg.price)} credits
                </Badge>
              )}
            </div>
            {pkg.description && (
              <p className="text-xs text-text-muted mb-2">{pkg.description}</p>
            )}
            <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-text-muted">
              {pkg.rtpMinute != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.rtpMinute)}</span> RPM
                </span>
              )}
              {pkg.rtpDay != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.rtpDay)}</span> RPD
                </span>
              )}
              {pkg.tokenLimitMonthly != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.tokenLimitMonthly)}</span> tokens/mo
                </span>
              )}
              {pkg.creditLimit != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.creditLimit)}</span> credits
                </span>
              )}
              {pkg.creditToTokenRatio != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.creditToTokenRatio)}</span> tok/credit
                </span>
              )}
              {pkg.maxConcurrent != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.maxConcurrent)}</span> concurrent
                </span>
              )}
              {pkg.durationDays != null && (
                <span>
                  <span className="font-medium text-text-main">{formatNumber(pkg.durationDays)}</span> days
                </span>
              )}
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          <Button size="sm" variant="ghost" icon="edit" onClick={onEdit}>
            Edit
          </Button>
          <Button size="sm" variant="danger" icon="delete" onClick={onDelete}>
            Delete
          </Button>
        </div>
      </div>
    </Card>
  );
}
