'use client';

import { useState, useEffect } from 'react';
import { Flag, Plus, Loader2, Trash2, ToggleLeft, ToggleRight } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } 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 { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

interface FlagDoc {
  id: string;
  productId: string;
  key: string;
  enabled: boolean;
  description: string;
  platforms: string[];
  segments: string[];
  percentage: number;
  createdAt: string;
  updatedAt: string;
}

export default function FlagsPage() {
  const [flags, setFlags] = useState<FlagDoc[]>([]);
  const [loading, setLoading] = useState(true);

  // Create dialog
  const [createOpen, setCreateOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState({
    key: '',
    description: '',
    enabled: true,
    percentage: 100,
    platforms: '',
  });

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

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

  const handleCreate = async () => {
    if (!form.key.trim()) return;
    setCreating(true);
    try {
      const res = await fetch('/api/flags', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          key: form.key.trim().toLowerCase().replace(/\s+/g, '_'),
          description: form.description,
          enabled: form.enabled,
          percentage: form.percentage,
          platforms: form.platforms
            ? form.platforms
                .split(',')
                .map(s => s.trim())
                .filter(Boolean)
            : [],
        }),
      });
      if (res.ok) {
        setCreateOpen(false);
        setForm({ key: '', description: '', enabled: true, percentage: 100, platforms: '' });
        loadFlags();
      }
    } catch {
      // ignore
    } finally {
      setCreating(false);
    }
  };

  const handleToggle = async (flag: FlagDoc) => {
    try {
      const res = await fetch(`/api/flags/${encodeURIComponent(flag.key)}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: !flag.enabled }),
      });
      if (res.ok) loadFlags();
    } catch {
      // ignore
    }
  };

  const handleUpdatePercentage = async (flag: FlagDoc, percentage: number) => {
    try {
      await fetch(`/api/flags/${encodeURIComponent(flag.key)}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ percentage }),
      });
      loadFlags();
    } catch {
      // ignore
    }
  };

  const handleDelete = async (flag: FlagDoc) => {
    if (!confirm(`Delete flag "${flag.key}"? This cannot be undone.`)) return;
    try {
      const res = await fetch(`/api/flags/${encodeURIComponent(flag.key)}`, { method: 'DELETE' });
      if (res.ok) loadFlags();
    } catch {
      // ignore
    }
  };

  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">Feature Flags</h1>
          <p className="text-muted-foreground">
            Control feature rollouts with percentage-based targeting
          </p>
        </div>
        <Dialog open={createOpen} onOpenChange={setCreateOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              New Flag
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create Feature Flag</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 pt-2">
              <div className="space-y-2">
                <Label>Key</Label>
                <Input
                  placeholder="enable_new_editor"
                  value={form.key}
                  onChange={e => setForm({ ...form, key: e.target.value })}
                />
                <p className="text-[10px] text-muted-foreground">
                  Lowercase, underscores only (e.g. enable_new_editor)
                </p>
              </div>
              <div className="space-y-2">
                <Label>Description</Label>
                <Input
                  placeholder="Enable the new rich text editor"
                  value={form.description}
                  onChange={e => setForm({ ...form, description: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>Platforms (comma-separated, optional)</Label>
                <Input
                  placeholder="desktop, ios, android, web"
                  value={form.platforms}
                  onChange={e => setForm({ ...form, platforms: e.target.value })}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>Enabled by default</Label>
                <Switch
                  checked={form.enabled}
                  onCheckedChange={v => setForm({ ...form, enabled: v })}
                />
              </div>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label>Rollout Percentage</Label>
                  <span className="text-sm font-mono">{form.percentage}%</span>
                </div>
                <Slider
                  value={[form.percentage]}
                  onValueChange={([v]: number[]) => setForm({ ...form, percentage: v })}
                  min={0}
                  max={100}
                  step={1}
                />
              </div>
              <Button
                className="w-full"
                onClick={handleCreate}
                disabled={creating || !form.key.trim()}
              >
                {creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Flag
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {flags.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground">
          <Flag className="mx-auto h-12 w-12 mb-3 opacity-30" />
          <p>No feature flags yet</p>
          <p className="text-xs mt-1">Create your first flag to control feature rollouts</p>
        </div>
      ) : (
        <div className="space-y-3">
          {flags.map(flag => (
            <Card key={flag.id}>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <button
                      onClick={() => handleToggle(flag)}
                      className="text-muted-foreground hover:text-foreground transition-colors"
                      title={flag.enabled ? 'Disable flag' : 'Enable flag'}
                    >
                      {flag.enabled ? (
                        <ToggleRight className="h-6 w-6 text-emerald-500" />
                      ) : (
                        <ToggleLeft className="h-6 w-6" />
                      )}
                    </button>
                    <div>
                      <CardTitle className="text-sm font-mono">{flag.key}</CardTitle>
                      {flag.description && (
                        <p className="text-xs text-muted-foreground mt-0.5">{flag.description}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge
                      variant="secondary"
                      className={
                        flag.enabled
                          ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400'
                          : 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400'
                      }
                    >
                      {flag.enabled ? 'ON' : 'OFF'}
                    </Badge>
                    <Badge variant="outline" className="font-mono text-xs">
                      {flag.percentage}%
                    </Badge>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                      onClick={() => handleDelete(flag)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="pt-0">
                <div className="flex items-center gap-4 text-xs text-muted-foreground">
                  {flag.platforms.length > 0 && <span>Platforms: {flag.platforms.join(', ')}</span>}
                  {flag.segments.length > 0 && <span>Segments: {flag.segments.join(', ')}</span>}
                  <span>Updated {new Date(flag.updatedAt).toLocaleDateString()}</span>
                </div>
                {flag.enabled && (
                  <div className="mt-3 flex items-center gap-3">
                    <span className="text-xs text-muted-foreground w-16">Rollout:</span>
                    <Slider
                      value={[flag.percentage]}
                      onValueChange={([v]: number[]) => handleUpdatePercentage(flag, v)}
                      min={0}
                      max={100}
                      step={1}
                      className="flex-1"
                    />
                    <span className="text-xs font-mono w-10 text-right">{flag.percentage}%</span>
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
