import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { KeyRound, CheckCircle2, XCircle, AlertCircle, Shield, ShieldOff } from "lucide-react";
import { cn } from "@/lib/utils";

export default function ActivationPage() {
  const { toast } = useToast();
  const [keyInput, setKeyInput] = useState("");

  const { data: status, isLoading } = useQuery({
    queryKey: ["/api/license/status"],
    queryFn: async () => {
      const res = await apiRequest("GET", "/api/license/status");
      return res.json() as Promise<{
        activated: boolean;
        expired: boolean;
        expiry: string | null;
        daysLeft: number | null;
      }>;
    },
  });

  const activateMutation = useMutation({
    mutationFn: async (key: string) => {
      const res = await apiRequest("POST", "/api/license/activate", { key });
      if (!res.ok) {
        const body = await res.json();
        throw new Error(body.error || "Activation failed");
      }
      return res.json();
    },
    onSuccess: () => {
      toast({ title: "License activated successfully" });
      setKeyInput("");
      queryClient.invalidateQueries({ queryKey: ["/api/license/status"] });
    },
    onError: (err: Error) => {
      toast({ title: err.message, variant: "destructive" });
    },
  });

  const formatExpiry = (expiry: string) => {
    return new Date(expiry).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  const isActive = status?.activated && !status?.expired;
  const isExpired = status?.activated && status?.expired;
  const isWarning = isActive && status?.daysLeft !== null && status.daysLeft <= 30;

  return (
    <div className="p-6 max-w-2xl mx-auto space-y-6">
      <div className="flex items-center space-x-3">
        <KeyRound className="h-6 w-6 text-gray-600" />
        <h1 className="text-2xl font-semibold text-gray-800">License Activation</h1>
      </div>

      {/* Status Card */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">License Status</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p className="text-gray-500 text-sm">Checking license...</p>
          ) : isActive ? (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <CheckCircle2 className="h-5 w-5 text-green-500" />
                <span className="font-medium text-green-700">Active</span>
              </div>
              <p className="text-sm text-gray-600">
                Expires: <span className="font-medium">{formatExpiry(status!.expiry!)}</span>
              </p>
              {isWarning && (
                <div className="flex items-center space-x-2 mt-2 p-2 bg-yellow-50 rounded-md border border-yellow-200">
                  <AlertCircle className="h-4 w-4 text-yellow-600 flex-shrink-0" />
                  <p className="text-sm text-yellow-700">
                    Expires in {status!.daysLeft} day{status!.daysLeft !== 1 ? "s" : ""}. Please renew soon.
                  </p>
                </div>
              )}
            </div>
          ) : isExpired ? (
            <div className="flex items-center space-x-2">
              <XCircle className="h-5 w-5 text-red-500" />
              <div>
                <span className="font-medium text-red-700">Expired</span>
                <p className="text-sm text-gray-500">
                  Expired on {formatExpiry(status!.expiry!)}. Enter a new key to reactivate.
                </p>
              </div>
            </div>
          ) : (
            <div className="flex items-center space-x-2">
              <XCircle className="h-5 w-5 text-gray-400" />
              <span className="text-gray-500">Not activated</span>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Activate Card */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Enter License Key</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <Input
            placeholder="DENTAL-XXXXXXXXXXXXXXXXXXXXXXXX-YYYY-MM-DD"
            value={keyInput}
            onChange={(e) => setKeyInput(e.target.value)}
            className="font-mono text-sm"
          />
          <Button
            onClick={() => activateMutation.mutate(keyInput)}
            disabled={!keyInput.trim() || activateMutation.isPending}
            className="w-full"
          >
            {activateMutation.isPending ? "Activating..." : "Activate"}
          </Button>
        </CardContent>
      </Card>

      {/* Features Card */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Features</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-2">Free</p>
            <div className="space-y-1">
              {[
                "MassHealth Eligibility",
                "MassHealth Claim",
                "Documents",
                "Payments",
                "Database Backups",
                "Reports",
              ].map((f) => (
                <div key={f} className="flex items-center space-x-2">
                  <CheckCircle2 className="h-4 w-4 text-green-500 flex-shrink-0" />
                  <span className="text-sm text-gray-700">{f}</span>
                </div>
              ))}
            </div>
          </div>

          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-2">Premium</p>
            <div className="space-y-1">
              {[
                "CCA, DDMA, United, Tufts Eligibility",
                "CCA, DDMA, United, Tufts Claims",
                "Pre-Authorizations",
                "AI SMS",
              ].map((f) => (
                <div key={f} className="flex items-center space-x-2">
                  {isActive ? (
                    <Shield className="h-4 w-4 text-blue-500 flex-shrink-0" />
                  ) : (
                    <ShieldOff className="h-4 w-4 text-gray-300 flex-shrink-0" />
                  )}
                  <span className={cn("text-sm", isActive ? "text-gray-700" : "text-gray-400")}>
                    {f}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
