'use client';

import { useEffect, useState, useCallback } from 'react';
import {
  Plus,
  RefreshCw,
  Trash2,
  Pencil,
  ToggleLeft,
  ToggleRight,
  Shield,
  Target,
  Clock,
  Percent,
  X,
} from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

// ─── Types ──────────────────────────────────────────────────────

interface TelemetryPolicy {
  id: string;
  productId: string;
  name: string;
  description?: string;
  enabled: boolean;
  priority: number;
  eventTypes: string[];
  modules: string[];
  samplingRate: number;
  targeting: {
    platforms?: string[];
    channels?: string[];
    osFamilies?: string[];
    appVersions?: string[];
    releaseChannels?: string[];
    percentage?: number;
  };
  startsAt?: string;
  expiresAt?: string;
  createdAt: string;
  updatedAt: string;
  createdBy?: string;
}

const EVENT_TYPES = ['debug', 'info', 'warn', 'error', 'fatal'];
const PLATFORMS = ['ios', 'android', 'macos', 'windows', 'linux', 'web'];
const CHANNELS = ['keyboard_extension', 'mobile_app', 'desktop_app', 'web_app'];
const RELEASE_CHANNELS = ['alpha', 'beta', 'stable'];

// ─── Component ──────────────────────────────────────────────────

export default function TelemetryPoliciesPage() {
  const [policies, setPolicies] = useState<TelemetryPolicy[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingPolicy, setEditingPolicy] = useState<TelemetryPolicy | null>(null);
  const [saving, setSaving] = useState(false);

  // Form state
  const [formName, setFormName] = useState('');
  const [formDescription, setFormDescription] = useState('');
  const [formEnabled, setFormEnabled] = useState(true);
  const [formPriority, setFormPriority] = useState(100);
  const [formEventTypes, setFormEventTypes] = useState<string[]>(['warn', 'error', 'fatal']);
  const [formModules, setFormModules] = useState('');
  const [formSamplingRate, setFormSamplingRate] = useState(1.0);
  const [formPlatforms, setFormPlatforms] = useState<string[]>([]);
  const [formChannels, setFormChannels] = useState<string[]>([]);
  const [formReleaseChannels, setFormReleaseChannels] = useState<string[]>([]);
  const [formPercentage, setFormPercentage] = useState(100);
  const [formStartsAt, setFormStartsAt] = useState('');
  const [formExpiresAt, setFormExpiresAt] = useState('');
  const [preview, setPreview] = useState<{
    matchedClients: number;
    totalClients: number;
    sampleSize: number;
  } | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  const fetchPolicies = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/telemetry/policies');
      if (res.ok) {
        const data = await res.json();
        setPolicies(data.policies ?? []);
      }
    } catch {
      // best effort
    } finally {
      setLoading(false);
    }
  }, []);

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

  const resetForm = () => {
    setFormName('');
    setFormDescription('');
    setFormEnabled(true);
    setFormPriority(100);
    setFormEventTypes(['warn', 'error', 'fatal']);
    setFormModules('');
    setFormSamplingRate(1.0);
    setFormPlatforms([]);
    setFormChannels([]);
    setFormReleaseChannels([]);
    setFormPercentage(100);
    setFormStartsAt('');
    setFormExpiresAt('');
    setEditingPolicy(null);
  };

  const openCreateForm = () => {
    resetForm();
    setShowForm(true);
  };

  const openEditForm = (policy: TelemetryPolicy) => {
    setEditingPolicy(policy);
    setFormName(policy.name);
    setFormDescription(policy.description ?? '');
    setFormEnabled(policy.enabled);
    setFormPriority(policy.priority);
    setFormEventTypes(policy.eventTypes);
    setFormModules(policy.modules.join(', '));
    setFormSamplingRate(policy.samplingRate);
    setFormPlatforms(policy.targeting.platforms ?? []);
    setFormChannels(policy.targeting.channels ?? []);
    setFormReleaseChannels(policy.targeting.releaseChannels ?? []);
    setFormPercentage(policy.targeting.percentage ?? 100);
    setFormStartsAt(policy.startsAt ?? '');
    setFormExpiresAt(policy.expiresAt ?? '');
    setShowForm(true);
  };

  const handleSave = async () => {
    setSaving(true);
    const body = {
      name: formName,
      description: formDescription || undefined,
      enabled: formEnabled,
      priority: formPriority,
      eventTypes: formEventTypes,
      modules: formModules
        ? formModules
            .split(',')
            .map(m => m.trim())
            .filter(Boolean)
        : [],
      samplingRate: formSamplingRate,
      targeting: {
        platforms: formPlatforms.length > 0 ? formPlatforms : undefined,
        channels: formChannels.length > 0 ? formChannels : undefined,
        releaseChannels: formReleaseChannels.length > 0 ? formReleaseChannels : undefined,
        percentage: formPercentage < 100 ? formPercentage : undefined,
      },
      startsAt: formStartsAt || undefined,
      expiresAt: formExpiresAt || undefined,
    };

    try {
      if (editingPolicy) {
        await fetch(`/api/telemetry/policies/${editingPolicy.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
      } else {
        await fetch('/api/telemetry/policies', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
      }
      setShowForm(false);
      resetForm();
      fetchPolicies();
    } catch {
      // best effort
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this policy?')) return;
    try {
      await fetch(`/api/telemetry/policies/${id}`, { method: 'DELETE' });
      fetchPolicies();
    } catch {
      // best effort
    }
  };

  const handleToggleEnabled = async (policy: TelemetryPolicy) => {
    try {
      await fetch(`/api/telemetry/policies/${policy.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: !policy.enabled }),
      });
      fetchPolicies();
    } catch {
      // best effort
    }
  };

  const toggleArrayItem = (arr: string[], item: string, setter: (v: string[]) => void) => {
    setter(arr.includes(item) ? arr.filter(x => x !== item) : [...arr, item]);
  };

  // ─── Render ───────────────────────────────────────────────────

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">Telemetry Policies</h2>
          <p className="text-muted-foreground">
            Control what telemetry data is collected from clients
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchPolicies}>
            <RefreshCw className="mr-2 h-4 w-4" />
            Refresh
          </Button>
          <Button size="sm" onClick={openCreateForm}>
            <Plus className="mr-2 h-4 w-4" />
            Create Policy
          </Button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Total Policies</CardDescription>
            <CardTitle className="text-3xl">{policies.length}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Active</CardDescription>
            <CardTitle className="text-3xl text-green-500">
              {policies.filter(p => p.enabled).length}
            </CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Disabled</CardDescription>
            <CardTitle className="text-3xl text-muted-foreground">
              {policies.filter(p => !p.enabled).length}
            </CardTitle>
          </CardHeader>
        </Card>
      </div>

      {/* Create/Edit Form */}
      {showForm && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle>{editingPolicy ? 'Edit Policy' : 'Create Policy'}</CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setShowForm(false);
                  resetForm();
                }}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Basic info */}
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <label className="text-sm font-medium">Name *</label>
                <Input
                  value={formName}
                  onChange={e => setFormName(e.target.value)}
                  placeholder="e.g. Collect errors from beta"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Description</label>
                <Input
                  value={formDescription}
                  onChange={e => setFormDescription(e.target.value)}
                  placeholder="Optional description"
                />
              </div>
            </div>

            {/* Priority + Sampling */}
            <div className="grid gap-4 md:grid-cols-3">
              <div className="space-y-2">
                <label className="text-sm font-medium flex items-center gap-1">
                  <Shield className="h-3.5 w-3.5" /> Priority
                </label>
                <Input
                  type="number"
                  value={formPriority}
                  onChange={e => setFormPriority(Number(e.target.value))}
                  min={0}
                  max={999}
                />
                <p className="text-xs text-muted-foreground">Higher = more important</p>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium flex items-center gap-1">
                  <Percent className="h-3.5 w-3.5" /> Sampling Rate
                </label>
                <Input
                  type="number"
                  value={formSamplingRate}
                  onChange={e => setFormSamplingRate(Number(e.target.value))}
                  min={0}
                  max={1}
                  step={0.1}
                />
                <p className="text-xs text-muted-foreground">0 = none, 1 = all</p>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Enabled</label>
                <Button
                  variant="outline"
                  className="w-full justify-start"
                  onClick={() => setFormEnabled(!formEnabled)}
                >
                  {formEnabled ? (
                    <ToggleRight className="mr-2 h-4 w-4 text-green-500" />
                  ) : (
                    <ToggleLeft className="mr-2 h-4 w-4 text-muted-foreground" />
                  )}
                  {formEnabled ? 'Enabled' : 'Disabled'}
                </Button>
              </div>
            </div>

            {/* Event Types */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Event Types</label>
              <div className="flex flex-wrap gap-2">
                {EVENT_TYPES.map(et => (
                  <Badge
                    key={et}
                    variant={formEventTypes.includes(et) ? 'default' : 'outline'}
                    className="cursor-pointer"
                    onClick={() => toggleArrayItem(formEventTypes, et, setFormEventTypes)}
                  >
                    {et}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Modules */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Modules (comma-separated)</label>
              <Input
                value={formModules}
                onChange={e => setFormModules(e.target.value)}
                placeholder="e.g. dictation, keyboard, app_lifecycle (empty = all)"
              />
            </div>

            {/* Targeting */}
            <div className="space-y-4">
              <h4 className="text-sm font-medium flex items-center gap-1">
                <Target className="h-3.5 w-3.5" /> Targeting Rules
              </h4>

              <div className="space-y-2">
                <label className="text-xs text-muted-foreground">Platforms</label>
                <div className="flex flex-wrap gap-2">
                  {PLATFORMS.map(p => (
                    <Badge
                      key={p}
                      variant={formPlatforms.includes(p) ? 'default' : 'outline'}
                      className="cursor-pointer"
                      onClick={() => toggleArrayItem(formPlatforms, p, setFormPlatforms)}
                    >
                      {p}
                    </Badge>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground">Empty = all platforms</p>
              </div>

              <div className="space-y-2">
                <label className="text-xs text-muted-foreground">Channels</label>
                <div className="flex flex-wrap gap-2">
                  {CHANNELS.map(c => (
                    <Badge
                      key={c}
                      variant={formChannels.includes(c) ? 'default' : 'outline'}
                      className="cursor-pointer"
                      onClick={() => toggleArrayItem(formChannels, c, setFormChannels)}
                    >
                      {c}
                    </Badge>
                  ))}
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-xs text-muted-foreground">Release Channels</label>
                <div className="flex flex-wrap gap-2">
                  {RELEASE_CHANNELS.map(rc => (
                    <Badge
                      key={rc}
                      variant={formReleaseChannels.includes(rc) ? 'default' : 'outline'}
                      className="cursor-pointer"
                      onClick={() =>
                        toggleArrayItem(formReleaseChannels, rc, setFormReleaseChannels)
                      }
                    >
                      {rc}
                    </Badge>
                  ))}
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-xs text-muted-foreground">
                  Percentage Rollout: {formPercentage}%
                </label>
                <input
                  type="range"
                  min={0}
                  max={100}
                  value={formPercentage}
                  onChange={e => setFormPercentage(Number(e.target.value))}
                  className="w-full"
                />
              </div>

              {/* Live Preview */}
              <div className="flex items-center gap-3">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={previewLoading}
                  onClick={async () => {
                    setPreviewLoading(true);
                    setPreview(null);
                    try {
                      const res = await fetch('/api/telemetry/policies/preview', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                          targeting: {
                            platforms: formPlatforms.length > 0 ? formPlatforms : undefined,
                            channels: formChannels.length > 0 ? formChannels : undefined,
                            releaseChannels:
                              formReleaseChannels.length > 0 ? formReleaseChannels : undefined,
                          },
                        }),
                      });
                      if (res.ok) setPreview(await res.json());
                    } catch {
                      /* best effort */
                    } finally {
                      setPreviewLoading(false);
                    }
                  }}
                >
                  <Target className="mr-1 h-3.5 w-3.5" />
                  {previewLoading ? 'Checking...' : 'Preview Match'}
                </Button>
                {preview && (
                  <span className="text-sm">
                    <strong className="text-primary">{preview.matchedClients}</strong>
                    <span className="text-muted-foreground">
                      {' '}
                      / {preview.totalClients} clients would match
                    </span>
                    <span className="text-xs text-muted-foreground ml-1">
                      (from {preview.sampleSize} recent events)
                    </span>
                  </span>
                )}
              </div>
            </div>

            {/* Scheduling */}
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <label className="text-sm font-medium flex items-center gap-1">
                  <Clock className="h-3.5 w-3.5" /> Starts At
                </label>
                <Input
                  type="datetime-local"
                  value={formStartsAt ? formStartsAt.slice(0, 16) : ''}
                  onChange={e =>
                    setFormStartsAt(e.target.value ? new Date(e.target.value).toISOString() : '')
                  }
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium flex items-center gap-1">
                  <Clock className="h-3.5 w-3.5" /> Expires At
                </label>
                <Input
                  type="datetime-local"
                  value={formExpiresAt ? formExpiresAt.slice(0, 16) : ''}
                  onChange={e =>
                    setFormExpiresAt(e.target.value ? new Date(e.target.value).toISOString() : '')
                  }
                />
              </div>
            </div>

            {/* Actions */}
            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => {
                  setShowForm(false);
                  resetForm();
                }}
              >
                Cancel
              </Button>
              <Button onClick={handleSave} disabled={!formName || saving}>
                {saving ? 'Saving...' : editingPolicy ? 'Update Policy' : 'Create Policy'}
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Policies Table */}
      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="space-y-3 p-6">
              {[1, 2, 3].map(i => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : policies.length === 0 ? (
            <div className="p-12 text-center text-muted-foreground">
              No policies yet. Create one to control telemetry collection.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Priority</TableHead>
                  <TableHead>Event Types</TableHead>
                  <TableHead>Sampling</TableHead>
                  <TableHead>Targeting</TableHead>
                  <TableHead>Schedule</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {policies
                  .sort((a, b) => b.priority - a.priority)
                  .map(policy => (
                    <TableRow key={policy.id}>
                      <TableCell>
                        <div>
                          <p className="font-medium">{policy.name}</p>
                          {policy.description && (
                            <p className="text-xs text-muted-foreground">{policy.description}</p>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={policy.enabled ? 'default' : 'secondary'}>
                          {policy.enabled ? 'Active' : 'Disabled'}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-mono">{policy.priority}</TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {policy.eventTypes.map(et => (
                            <Badge key={et} variant="outline" className="text-xs">
                              {et}
                            </Badge>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell className="font-mono">
                        {(policy.samplingRate * 100).toFixed(0)}%
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1 text-xs">
                          {policy.targeting.platforms?.map(p => (
                            <Badge key={p} variant="outline">
                              {p}
                            </Badge>
                          ))}
                          {policy.targeting.percentage !== undefined &&
                            policy.targeting.percentage < 100 && (
                              <Badge variant="outline">
                                {policy.targeting.percentage}% rollout
                              </Badge>
                            )}
                          {!policy.targeting.platforms?.length &&
                            policy.targeting.percentage === undefined && (
                              <span className="text-muted-foreground">All</span>
                            )}
                        </div>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {policy.startsAt ? new Date(policy.startsAt).toLocaleDateString() : '—'}
                        {' → '}
                        {policy.expiresAt ? new Date(policy.expiresAt).toLocaleDateString() : '∞'}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleToggleEnabled(policy)}
                            title={policy.enabled ? 'Disable' : 'Enable'}
                          >
                            {policy.enabled ? (
                              <ToggleRight className="h-4 w-4 text-green-500" />
                            ) : (
                              <ToggleLeft className="h-4 w-4" />
                            )}
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => openEditForm(policy)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => handleDelete(policy.id)}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
