'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Sparkles, Plus, Pencil, Trash2, Eye, EyeOff, Code } from 'lucide-react';
import { useState, useEffect } from 'react';

import { limitationsApi, type UpgradeTrigger, type TriggerKeyOption, type CreateUpgradeTriggerRequest, type UpdateUpgradeTriggerRequest } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';

interface TriggerFormData {
  trigger_key: string;
  title: string;
  message: string;
  promo_html: string;
  button_text: string;
  is_active: boolean;
}

const emptyFormData: TriggerFormData = {
  trigger_key: '',
  title: '',
  message: '',
  promo_html: '',
  button_text: 'Upgrade to Pro',
  is_active: true,
};

function TriggerFormDialog({
  trigger,
  triggerKeys,
  existingTriggerKeys,
  onSave,
  onClose,
  isOpen,
}: {
  trigger?: UpgradeTrigger;
  triggerKeys: TriggerKeyOption[];
  existingTriggerKeys: string[];
  onSave: (data: CreateUpgradeTriggerRequest | UpdateUpgradeTriggerRequest, id?: number) => void;
  onClose: () => void;
  isOpen: boolean;
}) {
  const [formData, setFormData] = useState<TriggerFormData>(emptyFormData);
  const [showPreview, setShowPreview] = useState(false);

  // Sync form data when trigger changes or dialog opens
  useEffect(() => {
    if (isOpen) {
      if (trigger) {
        setFormData({
          trigger_key: trigger.trigger_key || '',
          title: trigger.title || '',
          message: trigger.message || '',
          promo_html: trigger.promo_html || '',
          button_text: trigger.button_text || 'Upgrade to Pro',
          is_active: trigger.is_active ?? true,
        });
      } else {
        setFormData(emptyFormData);
      }
      setShowPreview(false);
    }
  }, [trigger, isOpen]);

  // For editing: always include the current trigger's key in available options
  // For creating: filter out already used keys
  const availableKeys = trigger
    ? triggerKeys // When editing, show all keys (user can change to any unused key)
    : triggerKeys.filter(k => !existingTriggerKeys.includes(k.key));

  const handleSave = () => {
    if (!formData.trigger_key || !formData.title || !formData.message) {
      toast.error('Please fill in all required fields');
      return;
    }

    if (trigger) {
      onSave(formData, trigger.id);
    } else {
      onSave(formData);
    }
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{trigger ? 'Edit' : 'Create'} Upgrade Trigger</DialogTitle>
          <DialogDescription>
            Configure the upgrade prompt that appears when users hit this trigger point.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="trigger_key">Trigger Point *</Label>
            <Select
              value={formData.trigger_key}
              onValueChange={(value) => setFormData(prev => ({ ...prev, trigger_key: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select trigger point" />
              </SelectTrigger>
              <SelectContent>
                {availableKeys.map((key) => (
                  <SelectItem key={key.key} value={key.key}>
                    {key.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="title">Title *</Label>
            <Input
              id="title"
              value={formData.title}
              onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
              placeholder="e.g., Unlock More Properties"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="message">Message *</Label>
            <Textarea
              id="message"
              value={formData.message}
              onChange={(e) => setFormData(prev => ({ ...prev, message: e.target.value }))}
              placeholder="e.g., Upgrade to Pro to add unlimited properties..."
              rows={3}
            />
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label htmlFor="promo_html">Promo HTML (Optional)</Label>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => setShowPreview(!showPreview)}
              >
                {showPreview ? <EyeOff className="h-4 w-4 mr-1" /> : <Eye className="h-4 w-4 mr-1" />}
                {showPreview ? 'Hide Preview' : 'Show Preview'}
              </Button>
            </div>
            <Textarea
              id="promo_html"
              value={formData.promo_html}
              onChange={(e) => setFormData(prev => ({ ...prev, promo_html: e.target.value }))}
              placeholder="<div>Rich HTML content for the upgrade prompt...</div>"
              rows={5}
              className="font-mono text-sm"
            />
            <p className="text-xs text-muted-foreground">
              Use HTML to create rich promotional content. Supports basic HTML tags.
            </p>
            {showPreview && formData.promo_html && (
              <Card className="mt-2">
                <CardHeader className="py-2">
                  <CardTitle className="text-sm flex items-center gap-2">
                    <Code className="h-4 w-4" />
                    HTML Preview
                  </CardTitle>
                </CardHeader>
                <CardContent className="py-2">
                  <div
                    className="prose prose-sm max-w-none"
                    dangerouslySetInnerHTML={{ __html: formData.promo_html }}
                  />
                </CardContent>
              </Card>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="button_text">Button Text</Label>
            <Input
              id="button_text"
              value={formData.button_text}
              onChange={(e) => setFormData(prev => ({ ...prev, button_text: e.target.value }))}
              placeholder="Upgrade to Pro"
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="is_active">Active</Label>
              <p className="text-xs text-muted-foreground">
                Only active triggers will be shown to users
              </p>
            </div>
            <Switch
              id="is_active"
              checked={formData.is_active}
              onCheckedChange={(checked) => setFormData(prev => ({ ...prev, is_active: checked }))}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSave}>
            {trigger ? 'Save Changes' : 'Create Trigger'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default function UpgradeTriggersPage() {
  const queryClient = useQueryClient();
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [editingTrigger, setEditingTrigger] = useState<UpgradeTrigger | null>(null);

  const { data: triggers, isLoading: triggersLoading } = useQuery({
    queryKey: ['upgrade-triggers'],
    queryFn: limitationsApi.listUpgradeTriggers,
  });

  const { data: triggerKeys, isLoading: keysLoading } = useQuery({
    queryKey: ['trigger-keys'],
    queryFn: limitationsApi.getAvailableTriggerKeys,
  });

  const createMutation = useMutation({
    mutationFn: limitationsApi.createUpgradeTrigger,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['upgrade-triggers'] });
      toast.success('Upgrade trigger created');
      setIsCreateOpen(false);
    },
    onError: (error: Error & { response?: { data?: { error?: string } } }) => {
      const message = error.response?.data?.error || error.message || 'Failed to create upgrade trigger';
      toast.error(message);
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: UpdateUpgradeTriggerRequest }) =>
      limitationsApi.updateUpgradeTrigger(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['upgrade-triggers'] });
      toast.success('Upgrade trigger updated');
      setEditingTrigger(null);
    },
    onError: (error: Error & { response?: { data?: { error?: string } } }) => {
      const message = error.response?.data?.error || error.message || 'Failed to update upgrade trigger';
      toast.error(message);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: limitationsApi.deleteUpgradeTrigger,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['upgrade-triggers'] });
      toast.success('Upgrade trigger deleted');
    },
    onError: () => {
      toast.error('Failed to delete upgrade trigger');
    },
  });

  const toggleActiveMutation = useMutation({
    mutationFn: ({ id, is_active }: { id: number; is_active: boolean }) =>
      limitationsApi.updateUpgradeTrigger(id, { is_active }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['upgrade-triggers'] });
      toast.success('Trigger status updated');
    },
    onError: () => {
      toast.error('Failed to update trigger status');
    },
  });

  const handleSave = (data: CreateUpgradeTriggerRequest | UpdateUpgradeTriggerRequest, id?: number) => {
    if (id) {
      updateMutation.mutate({ id, data });
    } else {
      createMutation.mutate(data as CreateUpgradeTriggerRequest);
    }
  };

  const existingTriggerKeys = triggers?.map(t => t.trigger_key) ?? [];

  const getTriggerLabel = (key: string): string => {
    return triggerKeys?.find(k => k.key === key)?.label ?? key;
  };

  if (triggersLoading || keysLoading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Upgrade Triggers</h1>
          <p className="text-muted-foreground">
            Configure upgrade prompts shown to free tier users at specific trigger points
          </p>
        </div>
        <Button onClick={() => setIsCreateOpen(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Add Trigger
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5" />
            Configured Triggers
          </CardTitle>
          <CardDescription>
            These prompts appear when free tier users try to access Pro features
          </CardDescription>
        </CardHeader>
        <CardContent>
          {triggers && triggers.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Trigger Point</TableHead>
                  <TableHead>Title</TableHead>
                  <TableHead>Has HTML</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {triggers.map((trigger) => (
                  <TableRow key={trigger.id}>
                    <TableCell className="font-medium">
                      {getTriggerLabel(trigger.trigger_key)}
                    </TableCell>
                    <TableCell>{trigger.title}</TableCell>
                    <TableCell>
                      {trigger.promo_html ? (
                        <Badge variant="secondary">
                          <Code className="h-3 w-3 mr-1" />
                          Yes
                        </Badge>
                      ) : (
                        <span className="text-muted-foreground">No</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <Switch
                        checked={trigger.is_active}
                        onCheckedChange={(checked) =>
                          toggleActiveMutation.mutate({ id: trigger.id, is_active: checked })
                        }
                      />
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setEditingTrigger(trigger)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>Delete Trigger?</AlertDialogTitle>
                              <AlertDialogDescription>
                                This will permanently delete the &quot;{trigger.title}&quot; upgrade trigger.
                                This action cannot be undone.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>Cancel</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => deleteMutation.mutate(trigger.id)}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                              >
                                Delete
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <Sparkles className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>No upgrade triggers configured yet.</p>
              <p className="text-sm">Click &quot;Add Trigger&quot; to create your first one.</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Info Box */}
      <Card className="bg-muted/50">
        <CardContent className="pt-6">
          <div className="text-sm text-muted-foreground space-y-2">
            <p><strong>Available Trigger Points:</strong></p>
            <ul className="list-disc list-inside space-y-1 ml-2">
              {triggerKeys?.map((key) => (
                <li key={key.key}>
                  <strong>{key.label}</strong> ({key.key})
                </li>
              ))}
            </ul>
          </div>
        </CardContent>
      </Card>

      {/* Create Dialog */}
      {isCreateOpen && triggerKeys && triggerKeys.length > 0 && (
        <TriggerFormDialog
          key="create-new"
          triggerKeys={triggerKeys}
          existingTriggerKeys={existingTriggerKeys}
          onSave={handleSave}
          onClose={() => setIsCreateOpen(false)}
          isOpen={isCreateOpen}
        />
      )}

      {/* Edit Dialog */}
      {editingTrigger && triggerKeys && triggerKeys.length > 0 && (
        <TriggerFormDialog
          key={editingTrigger.id}
          trigger={editingTrigger}
          triggerKeys={triggerKeys}
          existingTriggerKeys={existingTriggerKeys}
          onSave={handleSave}
          onClose={() => setEditingTrigger(null)}
          isOpen={!!editingTrigger}
        />
      )}
    </div>
  );
}
