'use client';

import { useState } from 'react';
import { Key, Search, Plus, Copy, Check, Loader2, Monitor, Smartphone, X } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface LicenseDoc {
  id: string;
  productId: string;
  key: string;
  userId: string;
  plan: 'free' | 'pro' | 'enterprise';
  status: 'active' | 'revoked' | 'expired';
  activatedAt: string | null;
  expiresAt: string | null;
  deviceIds: string[];
  maxDevices: number;
  createdAt: string;
  updatedAt: string;
}

const statusColors: Record<string, string> = {
  active: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400',
  revoked: 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400',
  expired: 'bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400',
};

const planColors: Record<string, string> = {
  free: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300',
  pro: 'bg-blue-50 text-blue-700 dark:bg-blue-950/30 dark:text-blue-400',
  enterprise: 'bg-purple-50 text-purple-700 dark:bg-purple-950/30 dark:text-purple-400',
};

export default function LicensesPage() {
  const [userId, setUserId] = useState('');
  const [licenses, setLicenses] = useState<LicenseDoc[]>([]);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  // Generate dialog state
  const [genOpen, setGenOpen] = useState(false);
  const [genUserId, setGenUserId] = useState('');
  const [genPlan, setGenPlan] = useState<'free' | 'pro' | 'enterprise'>('pro');
  const [genMaxDevices, setGenMaxDevices] = useState('3');
  const [generating, setGenerating] = useState(false);
  const [generatedKey, setGeneratedKey] = useState<string | null>(null);

  const handleSearch = async () => {
    if (!userId.trim()) return;
    setLoading(true);
    setSearched(true);
    try {
      const res = await fetch(`/api/licenses?userId=${encodeURIComponent(userId.trim())}`);
      if (res.ok) {
        const data = await res.json();
        setLicenses(data.licenses ?? []);
      } else {
        setLicenses([]);
      }
    } catch {
      setLicenses([]);
    } finally {
      setLoading(false);
    }
  };

  const handleGenerate = async () => {
    if (!genUserId.trim()) return;
    setGenerating(true);
    setGeneratedKey(null);
    try {
      const res = await fetch('/api/licenses', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: genUserId.trim(),
          plan: genPlan,
          maxDevices: Number(genMaxDevices) || 3,
        }),
      });
      if (res.ok) {
        const license = await res.json();
        setGeneratedKey(license.key);
        // Refresh search if same user
        if (userId.trim() === genUserId.trim()) {
          handleSearch();
        }
      }
    } catch {
      // ignore
    } finally {
      setGenerating(false);
    }
  };

  const handleRevokeLicense = async (key: string) => {
    if (!confirm('Revoke this license key? The user will lose access on all devices.')) return;
    try {
      const res = await fetch('/api/licenses', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key, action: 'revoke' }),
      });
      if (res.ok) {
        setLicenses(prev => prev.map(l => (l.key === key ? { ...l, status: 'revoked' } : l)));
      }
    } catch {
      // ignore
    }
  };

  const handleDeactivateDevice = async (key: string, deviceId: string) => {
    try {
      const res = await fetch('/api/licenses', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'deactivate', key, deviceId }),
      });
      if (res.ok) handleSearch();
    } catch {
      // ignore
    }
  };

  const copyToClipboard = async (key: string) => {
    await navigator.clipboard.writeText(key);
    setCopiedKey(key);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Licenses</h1>
          <p className="text-muted-foreground">
            Manage license keys — generate, view status, and deactivate devices
          </p>
        </div>
        <Dialog open={genOpen} onOpenChange={setGenOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Generate License
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Generate New License Key</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 pt-2">
              <div className="space-y-2">
                <Label>User ID</Label>
                <Input
                  placeholder="usr_..."
                  value={genUserId}
                  onChange={e => setGenUserId(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>Plan</Label>
                <Select value={genPlan} onValueChange={v => setGenPlan(v as typeof genPlan)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="free">Free</SelectItem>
                    <SelectItem value="pro">Pro</SelectItem>
                    <SelectItem value="enterprise">Enterprise</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Max Devices</Label>
                <Input
                  type="number"
                  min={1}
                  max={100}
                  value={genMaxDevices}
                  onChange={e => setGenMaxDevices(e.target.value)}
                />
              </div>
              {generatedKey && (
                <div className="rounded-lg border border-emerald-500/50 bg-emerald-50 dark:bg-emerald-950/30 p-4">
                  <p className="text-xs text-emerald-700 dark:text-emerald-300 mb-1">
                    License key generated:
                  </p>
                  <div className="flex items-center gap-2">
                    <code className="text-sm font-mono font-bold text-emerald-800 dark:text-emerald-200">
                      {generatedKey}
                    </code>
                    <Button variant="ghost" size="sm" onClick={() => copyToClipboard(generatedKey)}>
                      {copiedKey === generatedKey ? (
                        <Check className="h-4 w-4 text-emerald-600" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                </div>
              )}
              <Button
                className="w-full"
                onClick={handleGenerate}
                disabled={generating || !genUserId.trim()}
              >
                {generating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Generate
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Search */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Look Up Licenses</CardTitle>
          <CardDescription>Search by user ID to view their license keys</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="Enter user ID (e.g. usr_abc123...)"
              value={userId}
              onChange={e => setUserId(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              className="max-w-md"
            />
            <Button onClick={handleSearch} disabled={loading || !userId.trim()}>
              {loading ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Search className="mr-2 h-4 w-4" />
              )}
              Search
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Results */}
      {searched && !loading && licenses.length === 0 && (
        <div className="text-center py-12 text-muted-foreground">
          <Key className="mx-auto h-12 w-12 mb-3 opacity-30" />
          <p>No licenses found for this user</p>
        </div>
      )}

      {licenses.map(lic => (
        <Card key={lic.id}>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Key className="h-5 w-5 text-muted-foreground" />
                <div>
                  <div className="flex items-center gap-2">
                    <code className="text-sm font-mono font-bold">{lic.key}</code>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-6 w-6 p-0"
                      onClick={() => copyToClipboard(lic.key)}
                    >
                      {copiedKey === lic.key ? (
                        <Check className="h-3 w-3 text-emerald-600" />
                      ) : (
                        <Copy className="h-3 w-3" />
                      )}
                    </Button>
                  </div>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    Created {new Date(lic.createdAt).toLocaleDateString()}
                    {lic.expiresAt && (
                      <> · Expires {new Date(lic.expiresAt).toLocaleDateString()}</>
                    )}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Badge variant="secondary" className={planColors[lic.plan]}>
                  {lic.plan}
                </Badge>
                <Badge variant="secondary" className={statusColors[lic.status]}>
                  {lic.status}
                </Badge>
                {lic.status === 'active' && (
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-7 text-destructive hover:text-destructive border-destructive/30"
                    onClick={() => handleRevokeLicense(lic.key)}
                  >
                    Revoke
                  </Button>
                )}
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between text-sm mb-3">
              <span className="text-muted-foreground">
                Devices: {lic.deviceIds.length} / {lic.maxDevices}
              </span>
              {lic.activatedAt && (
                <span className="text-muted-foreground">
                  First activated {new Date(lic.activatedAt).toLocaleDateString()}
                </span>
              )}
            </div>
            {lic.deviceIds.length > 0 ? (
              <div className="space-y-2">
                {lic.deviceIds.map(deviceId => (
                  <div
                    key={deviceId}
                    className="flex items-center justify-between rounded-md border px-3 py-2"
                  >
                    <div className="flex items-center gap-2">
                      {deviceId.length > 12 ? (
                        <Monitor className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <Smartphone className="h-4 w-4 text-muted-foreground" />
                      )}
                      <code className="text-xs font-mono">{deviceId}</code>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 text-destructive hover:text-destructive"
                      onClick={() => handleDeactivateDevice(lic.key, deviceId)}
                    >
                      <X className="h-3 w-3 mr-1" />
                      Remove
                    </Button>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-xs text-muted-foreground italic">No devices activated yet</p>
            )}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
