import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, X } from 'lucide-react';
import { toast } from 'sonner';

interface ItemCategoryStructure {
  [category1: string]: {
    [category2: string]: string[];
  };
}

interface CategoryTabProps {
  itemCategories: ItemCategoryStructure;
  setItemCategories: (categories: ItemCategoryStructure) => void;
  newCategory1: string;
  setNewCategory1: (value: string) => void;
  newCategory2: string;
  setNewCategory2: (value: string) => void;
  newCategory3: string;
  setNewCategory3: (value: string) => void;
  selectedCategory1: string;
  setSelectedCategory1: (value: string) => void;
  selectedCategory2: string;
  setSelectedCategory2: (value: string) => void;
}

export function CategoryTab({
  itemCategories,
  setItemCategories,
  newCategory1,
  setNewCategory1,
  newCategory2,
  setNewCategory2,
  newCategory3,
  setNewCategory3,
  selectedCategory1,
  setSelectedCategory1,
  selectedCategory2,
  setSelectedCategory2
}: CategoryTabProps) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>품목분류 관리</CardTitle>
        <CardDescription>품목을 분류하는 카테고리를 관리합니다 (대분류 → 중분류 → 소분류)</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-6">
          {/* 대분류 추가 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-medium mb-3">대분류 추가</h3>
            <div className="flex gap-2">
              <Input
                placeholder="대분류명 입력"
                value={newCategory1}
                onChange={(e) => setNewCategory1(e.target.value)}
              />
              <Button onClick={() => {
                if (!newCategory1.trim()) return toast.error('대분류명을 입력해주세요');
                setItemCategories({ ...itemCategories, [newCategory1]: {} });
                setNewCategory1('');
                toast.success('대분류가 추가되었습니다');
              }}>
                <Plus className="w-4 h-4 mr-2" />
                추가
              </Button>
            </div>
          </div>

          {/* 대분류 목록 */}
          <div className="space-y-4">
            {Object.keys(itemCategories).map(cat1 => (
              <div key={cat1} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="font-medium text-lg">{cat1}</h3>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      const newCategories = { ...itemCategories };
                      delete newCategories[cat1];
                      setItemCategories(newCategories);
                      toast.success('삭제되었습니다');
                    }}
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </Button>
                </div>

                {/* 중분류 추가 */}
                <div className="ml-4 mb-3">
                  <div className="flex gap-2">
                    <Input
                      placeholder="중분류명 입력"
                      value={selectedCategory1 === cat1 ? newCategory2 : ''}
                      onChange={(e) => {
                        setSelectedCategory1(cat1);
                        setNewCategory2(e.target.value);
                      }}
                    />
                    <Button
                      size="sm"
                      onClick={() => {
                        if (!newCategory2.trim()) return toast.error('중분류명을 입력해주세요');
                        setItemCategories({
                          ...itemCategories,
                          [cat1]: { ...itemCategories[cat1], [newCategory2]: [] }
                        });
                        setNewCategory2('');
                        toast.success('중분류가 추가되었습니다');
                      }}
                    >
                      <Plus className="w-4 h-4 mr-2" />
                      추가
                    </Button>
                  </div>
                </div>

                {/* 중분류 목록 */}
                <div className="ml-4 space-y-3">
                  {Object.keys(itemCategories[cat1] || {}).map(cat2 => (
                    <div key={cat2} className="border-l-2 pl-4">
                      <div className="flex items-center justify-between mb-2">
                        <h4 className="font-medium">{cat2}</h4>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            const newCategories = { ...itemCategories };
                            delete newCategories[cat1][cat2];
                            setItemCategories(newCategories);
                            toast.success('삭제되었습니다');
                          }}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>

                      {/* 소분류 추가 */}
                      <div className="ml-4 mb-2">
                        <div className="flex gap-2">
                          <Input
                            placeholder="소분류명 입력"
                            value={selectedCategory1 === cat1 && selectedCategory2 === cat2 ? newCategory3 : ''}
                            onChange={(e) => {
                              setSelectedCategory1(cat1);
                              setSelectedCategory2(cat2);
                              setNewCategory3(e.target.value);
                            }}
                          />
                          <Button
                            size="sm"
                            onClick={() => {
                              if (!newCategory3.trim()) return toast.error('소분류명을 입력해주세요');
                              setItemCategories({
                                ...itemCategories,
                                [cat1]: {
                                  ...itemCategories[cat1],
                                  [cat2]: [...(itemCategories[cat1][cat2] || []), newCategory3]
                                }
                              });
                              setNewCategory3('');
                              toast.success('소분류가 추가되었습니다');
                            }}
                          >
                            <Plus className="w-4 h-4 mr-2" />
                            추가
                          </Button>
                        </div>
                      </div>

                      {/* 소분류 목록 */}
                      <div className="ml-4 flex flex-wrap gap-2">
                        {(itemCategories[cat1]?.[cat2] || []).map((cat3, idx) => (
                          <Badge key={idx} variant="secondary" className="flex items-center gap-1">
                            {cat3}
                            <button
                              onClick={() => {
                                const newCategories = { ...itemCategories };
                                newCategories[cat1][cat2] = newCategories[cat1][cat2].filter(c => c !== cat3);
                                setItemCategories(newCategories);
                                toast.success('삭제되었습니다');
                              }}
                              className="ml-1 hover:text-red-500"
                            >
                              <X className="w-3 h-3" />
                            </button>
                          </Badge>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}