import React, { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { __ } from '@/lib/i18n';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';

type OrganizationTabProps = {
  categories: any[];
  selectedCategories: number[];
  setSelectedCategories: (value: number[]) => void;
  tags: any[];
  selectedTags: number[];
  setSelectedTags: (value: number[]) => void;
};

export function OrganizationTab({
  categories,
  selectedCategories,
  setSelectedCategories,
  tags,
  selectedTags,
  setSelectedTags,
}: OrganizationTabProps) {
  const queryClient = useQueryClient();
  const [newCategoryName, setNewCategoryName] = useState('');
  const [newTagName, setNewTagName] = useState('');
  const [creatingCategory, setCreatingCategory] = useState(false);
  const [creatingTag, setCreatingTag] = useState(false);

  const handleCreateCategory = async () => {
    if (!newCategoryName.trim()) {
      toast.error(__('Please enter a category name'));
      return;
    }

    setCreatingCategory(true);
    try {
      const response = await api.post('/products/categories', { name: newCategoryName.trim() });
      toast.success(__('Category created successfully'));
      setNewCategoryName('');
      // Auto-select the new category
      if (response.id) {
        setSelectedCategories([...selectedCategories, response.id]);
      }
      // Invalidate categories query to refresh the list
      queryClient.invalidateQueries({ queryKey: ['product-categories'] });
    } catch (error: any) {
      toast.error(error.message || __('Failed to create category'));
    } finally {
      setCreatingCategory(false);
    }
  };

  const handleCreateTag = async () => {
    if (!newTagName.trim()) {
      toast.error(__('Please enter a tag name'));
      return;
    }

    setCreatingTag(true);
    try {
      const response = await api.post('/products/tags', { name: newTagName.trim() });
      toast.success(__('Tag created successfully'));
      setNewTagName('');
      // Auto-select the new tag
      if (response.id) {
        setSelectedTags([...selectedTags, response.id]);
      }
      // Note: Parent component should refetch tags
    } catch (error: any) {
      toast.error(error.message || __('Failed to create tag'));
    } finally {
      setCreatingTag(false);
    }
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{__('Categories')}</CardTitle>
          <CardDescription>{__('Organize your product into categories')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Create New Category */}
          <div className="flex gap-2">
            <Input
              placeholder={__('New category name...')}
              value={newCategoryName}
              onChange={(e) => setNewCategoryName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  handleCreateCategory();
                }
              }}
            />
            <Button
              type="button"
              onClick={handleCreateCategory}
              disabled={creatingCategory || !newCategoryName.trim()}
              size="sm"
            >
              <Plus className="w-4 h-4 mr-1" />
              {__('Add')}
            </Button>
          </div>

          {/* Existing Categories */}
          {categories.length === 0 ? (
            <p className="text-sm text-muted-foreground">{__('No categories yet. Create one above!')}</p>
          ) : (
            <div className="space-y-2">
              {categories.map((cat: any) => (
                <div key={cat.id} className="flex items-center space-x-2">
                  <Checkbox
                    id={`cat-${cat.id}`}
                    checked={selectedCategories.includes(cat.id)}
                    onCheckedChange={(checked) => {
                      if (checked) {
                        setSelectedCategories([...selectedCategories, cat.id]);
                      } else {
                        setSelectedCategories(selectedCategories.filter(id => id !== cat.id));
                      }
                    }}
                  />
                  <Label htmlFor={`cat-${cat.id}`} className="cursor-pointer font-normal">
                    {cat.name}
                  </Label>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{__('Tags')}</CardTitle>
          <CardDescription>{__('Add tags to help customers find your product')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Create New Tag */}
          <div className="flex gap-2">
            <Input
              placeholder={__('New tag name...')}
              value={newTagName}
              onChange={(e) => setNewTagName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  handleCreateTag();
                }
              }}
            />
            <Button
              type="button"
              onClick={handleCreateTag}
              disabled={creatingTag || !newTagName.trim()}
              size="sm"
            >
              <Plus className="w-4 h-4 mr-1" />
              {__('Add')}
            </Button>
          </div>

          {/* Existing Tags */}
          {tags.length === 0 ? (
            <p className="text-sm text-muted-foreground">{__('No tags yet. Create one above!')}</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {tags.map((tag: any) => (
                <button
                  key={tag.id}
                  type="button"
                  onClick={() => {
                    if (selectedTags.includes(tag.id)) {
                      setSelectedTags(selectedTags.filter(id => id !== tag.id));
                    } else {
                      setSelectedTags([...selectedTags, tag.id]);
                    }
                  }}
                  className={`px-3 py-1 rounded-full text-sm border transition-colors ${selectedTags.includes(tag.id)
                      ? 'bg-primary text-primary-foreground border-primary'
                      : 'bg-background border-border hover:bg-accent'
                    }`}
                >
                  {tag.name}
                </button>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
