'use client';

import { useState, useEffect } from 'react';
import {
  Package,
  Plus,
  Loader2,
  Check,
  X,
  Globe,
  Edit2,
  Rocket,
  CheckCircle2,
  Trash2,
} 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 ProductDoc {
  id: string;
  productId: string;
  displayName: string;
  licensePrefix: string;
  packageName: string;
  defaultPlan: 'free' | 'pro';
  trialDays: number;
  deviceLimits: { free: number; pro: number; enterprise: number };
  websiteUrl: string;
  status: 'active' | 'disabled';
  createdAt: string;
  updatedAt: string;
}

export default function ProductsPage() {
  const [products, setProducts] = useState<ProductDoc[]>([]);
  const [loading, setLoading] = useState(true);

  // Create dialog
  const [createOpen, setCreateOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState({
    productId: '',
    displayName: '',
    licensePrefix: '',
    packageName: '',
    defaultPlan: 'free' as 'free' | 'pro',
    trialDays: '14',
    websiteUrl: '',
    deviceLimitFree: '1',
    deviceLimitPro: '3',
    deviceLimitEnterprise: '10',
  });

  // Edit dialog
  const [editProduct, setEditProduct] = useState<ProductDoc | null>(null);
  const [editForm, setEditForm] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);

  // Onboarding state
  const [onboarding, setOnboarding] = useState<string | null>(null);
  const [onboardResult, setOnboardResult] = useState<{
    productId: string;
    plans: number;
    flags: number;
  } | null>(null);

  const loadProducts = async () => {
    try {
      const res = await fetch('/api/products');
      if (res.ok) {
        const data = await res.json();
        setProducts(data.products ?? []);
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProducts();
  }, []);

  const handleCreate = async () => {
    setCreating(true);
    try {
      const res = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          productId: form.productId,
          displayName: form.displayName,
          licensePrefix: form.licensePrefix,
          packageName: form.packageName,
          defaultPlan: form.defaultPlan,
          trialDays: Number(form.trialDays) || 14,
          websiteUrl: form.websiteUrl || '',
          deviceLimits: {
            free: Number(form.deviceLimitFree) || 1,
            pro: Number(form.deviceLimitPro) || 3,
            enterprise: Number(form.deviceLimitEnterprise) || 10,
          },
        }),
      });
      if (res.ok) {
        const product = await res.json();
        setCreateOpen(false);
        setForm({
          productId: '',
          displayName: '',
          licensePrefix: '',
          packageName: '',
          defaultPlan: 'free',
          trialDays: '14',
          websiteUrl: '',
          deviceLimitFree: '1',
          deviceLimitPro: '3',
          deviceLimitEnterprise: '10',
        });
        // Auto-onboard: seed plans + kill_switch flag
        await handleOnboard(product.productId);
        loadProducts();
      }
    } catch {
      // ignore
    } finally {
      setCreating(false);
    }
  };

  const handleOnboard = async (productId: string) => {
    setOnboarding(productId);
    setOnboardResult(null);
    try {
      const res = await fetch(`/api/products/${productId}/onboard`, { method: 'POST' });
      if (res.ok) {
        const data = await res.json();
        setOnboardResult({
          productId,
          plans: data.plans?.length ?? 0,
          flags: data.flags?.length ?? 0,
        });
        setTimeout(() => setOnboardResult(null), 8000);
      }
    } catch {
      // ignore
    } finally {
      setOnboarding(null);
    }
  };

  const openEdit = (p: ProductDoc) => {
    setEditProduct(p);
    setEditForm({
      displayName: p.displayName,
      trialDays: String(p.trialDays),
      defaultPlan: p.defaultPlan,
      status: p.status,
      websiteUrl: p.websiteUrl,
      deviceLimitFree: String(p.deviceLimits.free),
      deviceLimitPro: String(p.deviceLimits.pro),
      deviceLimitEnterprise: String(p.deviceLimits.enterprise),
    });
  };

  const handleDelete = async (productId: string) => {
    if (!confirm(`Delete product "${productId}"? This cannot be undone.`)) return;
    try {
      const res = await fetch(`/api/products/${productId}`, { method: 'DELETE' });
      if (res.ok) {
        setProducts(prev => prev.filter(p => p.productId !== productId && p.id !== productId));
      }
    } catch {
      // ignore
    }
  };

  const handleUpdate = async () => {
    if (!editProduct) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/products/${editProduct.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          displayName: editForm.displayName,
          trialDays: Number(editForm.trialDays),
          defaultPlan: editForm.defaultPlan,
          status: editForm.status,
          websiteUrl: editForm.websiteUrl || '',
          deviceLimits: {
            free: Number(editForm.deviceLimitFree),
            pro: Number(editForm.deviceLimitPro),
            enterprise: Number(editForm.deviceLimitEnterprise),
          },
        }),
      });
      if (res.ok) {
        setEditProduct(null);
        loadProducts();
      }
    } catch {
      // ignore
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Products</h1>
          <p className="text-muted-foreground">Manage registered products in the platform</p>
        </div>
        <Dialog open={createOpen} onOpenChange={setCreateOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Add Product
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>Register New Product</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 pt-2 max-h-[60vh] overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Product ID</Label>
                  <Input
                    placeholder="my-product"
                    value={form.productId}
                    onChange={e => setForm({ ...form, productId: e.target.value })}
                  />
                  <p className="text-[10px] text-muted-foreground">Lowercase, no spaces</p>
                </div>
                <div className="space-y-2">
                  <Label>Display Name</Label>
                  <Input
                    placeholder="My Product"
                    value={form.displayName}
                    onChange={e => setForm({ ...form, displayName: e.target.value })}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>License Prefix</Label>
                  <Input
                    placeholder="PROD"
                    value={form.licensePrefix}
                    onChange={e =>
                      setForm({ ...form, licensePrefix: e.target.value.toUpperCase() })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label>Package Name</Label>
                  <Input
                    placeholder="com.bytelyst.myproduct"
                    value={form.packageName}
                    onChange={e => setForm({ ...form, packageName: e.target.value })}
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Default Plan</Label>
                  <Select
                    value={form.defaultPlan}
                    onValueChange={v => setForm({ ...form, defaultPlan: v as 'free' | 'pro' })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="free">Free</SelectItem>
                      <SelectItem value="pro">Pro</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Trial Days</Label>
                  <Input
                    type="number"
                    min={0}
                    max={365}
                    value={form.trialDays}
                    onChange={e => setForm({ ...form, trialDays: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Website URL</Label>
                <Input
                  placeholder="https://example.com"
                  value={form.websiteUrl}
                  onChange={e => setForm({ ...form, websiteUrl: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>Device Limits</Label>
                <div className="grid grid-cols-3 gap-2">
                  <div>
                    <p className="text-[10px] text-muted-foreground mb-1">Free</p>
                    <Input
                      type="number"
                      min={0}
                      value={form.deviceLimitFree}
                      onChange={e => setForm({ ...form, deviceLimitFree: e.target.value })}
                    />
                  </div>
                  <div>
                    <p className="text-[10px] text-muted-foreground mb-1">Pro</p>
                    <Input
                      type="number"
                      min={0}
                      value={form.deviceLimitPro}
                      onChange={e => setForm({ ...form, deviceLimitPro: e.target.value })}
                    />
                  </div>
                  <div>
                    <p className="text-[10px] text-muted-foreground mb-1">Enterprise</p>
                    <Input
                      type="number"
                      min={0}
                      value={form.deviceLimitEnterprise}
                      onChange={e => setForm({ ...form, deviceLimitEnterprise: e.target.value })}
                    />
                  </div>
                </div>
              </div>
              <Button
                className="w-full"
                onClick={handleCreate}
                disabled={creating || !form.productId || !form.displayName || !form.licensePrefix}
              >
                {creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Product
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Onboarding success banner */}
      {onboardResult && (
        <div className="flex items-center gap-3 rounded-lg border border-emerald-500/50 bg-emerald-50 dark:bg-emerald-950/30 p-4">
          <CheckCircle2 className="h-5 w-5 text-emerald-600 shrink-0" />
          <div>
            <p className="text-sm font-medium text-emerald-800 dark:text-emerald-200">
              Product &quot;{onboardResult.productId}&quot; onboarded successfully
            </p>
            <p className="text-xs text-emerald-700 dark:text-emerald-300">
              {onboardResult.plans} plans seeded
              {onboardResult.flags > 0 ? `, ${onboardResult.flags} flag(s) created` : ''}
            </p>
          </div>
        </div>
      )}

      {products.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground">
          <Package className="mx-auto h-12 w-12 mb-3 opacity-30" />
          <p>No products registered yet</p>
          <p className="text-xs mt-1">Create your first product to get started</p>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2">
          {products.map(p => (
            <Card key={p.id}>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                      <Package className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-base">{p.displayName}</CardTitle>
                      <CardDescription className="font-mono text-xs">{p.productId}</CardDescription>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge
                      variant="secondary"
                      className={
                        p.status === 'active'
                          ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400'
                          : 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400'
                      }
                    >
                      {p.status === 'active' ? (
                        <Check className="mr-1 h-3 w-3" />
                      ) : (
                        <X className="mr-1 h-3 w-3" />
                      )}
                      {p.status}
                    </Badge>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleOnboard(p.productId)}
                      disabled={onboarding === p.productId}
                      title="Seed plans & flags"
                    >
                      {onboarding === p.productId ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Rocket className="h-4 w-4" />
                      )}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => openEdit(p)}>
                      <Edit2 className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="text-destructive hover:text-destructive"
                      onClick={() => handleDelete(p.id)}
                      title="Delete product"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-y-2 text-sm">
                  <div className="text-muted-foreground">License Prefix</div>
                  <div className="font-mono">{p.licensePrefix}-XXXX-XXXX-XXXX</div>
                  <div className="text-muted-foreground">Default Plan</div>
                  <div className="capitalize">{p.defaultPlan}</div>
                  <div className="text-muted-foreground">Trial Days</div>
                  <div>{p.trialDays}</div>
                  <div className="text-muted-foreground">Device Limits</div>
                  <div>
                    Free: {p.deviceLimits.free} · Pro: {p.deviceLimits.pro} · Ent:{' '}
                    {p.deviceLimits.enterprise}
                  </div>
                  {p.websiteUrl && (
                    <>
                      <div className="text-muted-foreground">Website</div>
                      <a
                        href={p.websiteUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-primary hover:underline flex items-center gap-1"
                      >
                        <Globe className="h-3 w-3" />
                        {p.websiteUrl.replace(/^https?:\/\//, '')}
                      </a>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Edit Dialog */}
      <Dialog open={!!editProduct} onOpenChange={open => !open && setEditProduct(null)}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Edit {editProduct?.displayName}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 pt-2">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Display Name</Label>
                <Input
                  value={editForm.displayName ?? ''}
                  onChange={e => setEditForm({ ...editForm, displayName: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>Status</Label>
                <Select
                  value={editForm.status ?? 'active'}
                  onValueChange={v => setEditForm({ ...editForm, status: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="disabled">Disabled</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Default Plan</Label>
                <Select
                  value={editForm.defaultPlan ?? 'free'}
                  onValueChange={v => setEditForm({ ...editForm, defaultPlan: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="free">Free</SelectItem>
                    <SelectItem value="pro">Pro</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Trial Days</Label>
                <Input
                  type="number"
                  min={0}
                  max={365}
                  value={editForm.trialDays ?? '14'}
                  onChange={e => setEditForm({ ...editForm, trialDays: e.target.value })}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Website URL</Label>
              <Input
                value={editForm.websiteUrl ?? ''}
                onChange={e => setEditForm({ ...editForm, websiteUrl: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label>Device Limits</Label>
              <div className="grid grid-cols-3 gap-2">
                <div>
                  <p className="text-[10px] text-muted-foreground mb-1">Free</p>
                  <Input
                    type="number"
                    min={0}
                    value={editForm.deviceLimitFree ?? '1'}
                    onChange={e => setEditForm({ ...editForm, deviceLimitFree: e.target.value })}
                  />
                </div>
                <div>
                  <p className="text-[10px] text-muted-foreground mb-1">Pro</p>
                  <Input
                    type="number"
                    min={0}
                    value={editForm.deviceLimitPro ?? '3'}
                    onChange={e => setEditForm({ ...editForm, deviceLimitPro: e.target.value })}
                  />
                </div>
                <div>
                  <p className="text-[10px] text-muted-foreground mb-1">Enterprise</p>
                  <Input
                    type="number"
                    min={0}
                    value={editForm.deviceLimitEnterprise ?? '10'}
                    onChange={e =>
                      setEditForm({ ...editForm, deviceLimitEnterprise: e.target.value })
                    }
                  />
                </div>
              </div>
            </div>
            <Button className="w-full" onClick={handleUpdate} disabled={saving}>
              {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save Changes
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
