import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Pencil, Trash2, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { api } from '@/lib/api';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';

interface Tag {
  term_id: number;
  name: string;
  slug: string;
  description: string;
  count: number;
}

export default function ProductTags() {
  const queryClient = useQueryClient();
  const [search, setSearch] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);
  const [formData, setFormData] = useState({ name: '', slug: '', description: '' });
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<number | null>(null);

  const { data: tags = [], isLoading } = useQuery<Tag[]>({
    queryKey: ['product-tags'],
    queryFn: async () => {
      const response = await fetch(`${api.root()}/products/tags`, {
        headers: { 'X-WP-Nonce': api.nonce() },
      });
      return response.json();
    },
  });

  const createMutation = useMutation({
    mutationFn: (data: any) => api.post('/products/tags', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['product-tags'] });
      toast.success(__('Tag created successfully'));
      handleCloseDialog();
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to create tag'));
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: any }) => api.put(`/products/tags/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['product-tags'] });
      toast.success(__('Tag updated successfully'));
      handleCloseDialog();
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to update tag'));
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => api.del(`/products/tags/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['product-tags'] });
      toast.success(__('Tag deleted successfully'));
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to delete tag'));
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    },
  });

  const handleOpenDialog = (tag?: Tag) => {
    if (tag) {
      setEditingTag(tag);
      setFormData({
        name: tag.name,
        slug: tag.slug,
        description: tag.description || '',
      });
    } else {
      setEditingTag(null);
      setFormData({ name: '', slug: '', description: '' });
    }
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditingTag(null);
    setFormData({ name: '', slug: '', description: '' });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (editingTag) {
      updateMutation.mutate({ id: editingTag.term_id, data: formData });
    } else {
      createMutation.mutate(formData);
    }
  };

  const handleDeleteClick = (id: number) => {
    setDeleteTargetId(id);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTargetId) {
      deleteMutation.mutate(deleteTargetId);
    }
  };

  const filteredTags = tags.filter((tag) =>
    tag.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{__('Product Tags')}</h1>
        <Button onClick={() => handleOpenDialog()}>
          <Plus className="w-4 h-4 mr-2" />
          {__('Add Tag')}
        </Button>
      </div>

      <div className="flex items-center gap-2">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder={__('Search tags...')}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="!pl-9"
          />
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-8">
          <p className="text-muted-foreground">{__('Loading tags...')}</p>
        </div>
      ) : filteredTags.length === 0 ? (
        <div className="text-center py-8 border rounded-lg">
          <p className="text-muted-foreground">{__('No tags found')}</p>
        </div>
      ) : (
        <div className="border rounded-lg">
          <table className="w-full">
            <thead className="bg-muted/50">
              <tr>
                <th className="text-left p-4 font-medium">{__('Name')}</th>
                <th className="text-left p-4 font-medium">{__('Slug')}</th>
                <th className="text-left p-4 font-medium">{__('Description')}</th>
                <th className="text-center p-4 font-medium">{__('Count')}</th>
                <th className="text-right p-4 font-medium">{__('Actions')}</th>
              </tr>
            </thead>
            <tbody>
              {filteredTags.map((tag, index) => (
                <tr key={tag.term_id || `tag-${index}`} className="border-t hover:bg-muted/30">
                  <td className="p-4 font-medium">{tag.name}</td>
                  <td className="p-4 text-muted-foreground">{tag.slug}</td>
                  <td className="p-4 text-sm text-muted-foreground">
                    {tag.description || '-'}
                  </td>
                  <td className="p-4 text-center">{tag.count}</td>
                  <td className="p-4">
                    <div className="flex items-center justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleOpenDialog(tag)}
                      >
                        <Pencil className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick(tag.term_id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {editingTag ? __('Edit Tag') : __('Add Tag')}
            </DialogTitle>
            <DialogDescription>
              {editingTag ? __('Update tag information') : __('Create a new product tag')}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4 px-6 py-4">
            <div>
              <Label htmlFor="name">{__('Name')}</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                required
              />
            </div>
            <div>
              <Label htmlFor="slug">{__('Slug')}</Label>
              <Input
                id="slug"
                value={formData.slug}
                onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                placeholder={__('Leave empty to auto-generate')}
              />
            </div>
            <div>
              <Label htmlFor="description">{__('Description')}</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                rows={3}
              />
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={handleCloseDialog}>
                {__('Cancel')}
              </Button>
              <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
                {editingTag ? __('Update') : __('Create')}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
