All files / varjoliitokauppa/pages Admin.tsx

19.66% Statements 35/178
5.26% Branches 7/133
2.98% Functions 2/67
20.34% Lines 35/172

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893                      2x 2x 2x 2x 2x     2x 2x 2x 2x     2x 2x 2x 2x 2x     2x                             2x                 2x 2x               2x                   2x                   2x                   2x                   2x                             2x             2x                                                                         2x                     2x                                   2x                         2x                         2x             2x                                               2x                         2x             2x 2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
'use client';
 
import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import { Section } from '../components/Section';
import { Product, AdminReview, AdminOrder, CategoryImage } from '../types';
import { CATEGORIES, CATEGORY_IMAGE_DEFAULTS } from '../constants';
import { signIn, signOut, useSession } from 'next-auth/react';
import { PlusCircle, Edit2, Trash2, Save, X } from 'lucide-react';
import { ImageUpload } from '../components/ImageUpload';
 
const Admin: React.FC = () => {
  const { data: session, status } = useSession();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
 
  // Data states
  const [products, setProducts] = useState<Product[]>([]);
  const [reviews, setReviews] = useState<AdminReview[]>([]);
  const [orders, setOrders] = useState<AdminOrder[]>([]);
  const [categoryImages, setCategoryImages] = useState<CategoryImage[]>([]);
 
  // UI states
  const [activeTab, setActiveTab] = useState<'products' | 'reviews' | 'orders' | 'category-images'>('products');
  const [showProductForm, setShowProductForm] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [showCategoryImageForm, setShowCategoryImageForm] = useState(false);
  const [editingCategory, setEditingCategory] = useState<string>('');
 
  // Form state
  const [formData, setFormData] = useState<Partial<Product>>({
    name: '',
    price: 0,
    category: '',
    subcategory: '',
    shortDescription: '',
    description: '',
    images: [],
    stock: 0,
    brand: '',
    isNew: false,
    isUsed: false,
  });
 
  // Category image form state
  const [categoryImageForm, setCategoryImageForm] = useState<{
    categoryName: string;
    imageUrl: string;
  }>({
    categoryName: '',
    imageUrl: '',
  });
 
  // Load data when authenticated
  useEffect(() => {
    Iif (status === 'authenticated') {
      fetchProducts();
      fetchReviews();
      fetchOrders();
      fetchCategoryImages();
    }
  }, [status]);
 
  const fetchProducts = async () => {
    try {
      const res = await fetch('/api/products');
      const data = await res.json();
      setProducts(data);
    } catch (error) {
      console.error('Error fetching products:', error);
    }
  };
 
  const fetchReviews = async () => {
    try {
      const res = await fetch('/api/admin/reviews');
      const data = await res.json();
      setReviews(data);
    } catch (error) {
      console.error('Error fetching reviews:', error);
    }
  };
 
  const fetchOrders = async () => {
    try {
      const res = await fetch('/api/admin/orders');
      const data = await res.json();
      setOrders(data);
    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  };
 
  const fetchCategoryImages = async () => {
    try {
      const res = await fetch('/api/admin/category-images');
      const data = await res.json();
      setCategoryImages(data);
    } catch (error) {
      console.error('Error fetching category images:', error);
    }
  };
 
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
 
    const result = await signIn('credentials', {
      email,
      password,
      redirect: false,
    });
 
    if (result?.error) {
      setError('Virheellinen sähköposti tai salasana');
    }
  };
 
  const handleImagesChange = (newImages: string[]) => {
    setFormData(prev => ({
      ...prev,
      images: newImages,
    }));
  };
 
  const handleSaveProduct = async () => {
    try {
      const url = editingProduct
        ? `/api/admin/products/${editingProduct.id}`
        : '/api/admin/products';
 
      const method = editingProduct ? 'PUT' : 'POST';
 
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
 
      if (res.ok) {
        await fetchProducts();
        setShowProductForm(false);
        setEditingProduct(null);
        setFormData({
          name: '',
          price: 0,
          category: '',
          subcategory: '',
          shortDescription: '',
          description: '',
          images: [],
          stock: 0,
          brand: '',
          isNew: false,
          isUsed: false,
        });
      }
    } catch (error) {
      console.error('Error saving product:', error);
    }
  };
 
  const handleDeleteProduct = async (id: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän tuotteen?')) return;
 
    try {
      await fetch(`/api/admin/products/${id}`, { method: 'DELETE' });
      await fetchProducts();
    } catch (error) {
      console.error('Error deleting product:', error);
    }
  };
 
  const handleEditProduct = (product: Product) => {
    setEditingProduct(product);
    setFormData({
      ...product,
      brand: product.brand ?? '',
      category: product.category ?? '',
      subcategory: product.subcategory ?? '',
      shortDescription: product.shortDescription ?? '',
      description: product.description ?? '',
      images: product.images ?? [],
      stock: product.stock ?? 0,
      price: product.price ?? 0,
      isNew: product.isNew ?? false,
      isUsed: product.isUsed ?? false,
    });
    setShowProductForm(true);
  };
 
  const handleReviewAction = async (id: string, status: 'approved' | 'rejected') => {
    try {
      await fetch(`/api/admin/reviews/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      await fetchReviews();
    } catch (error) {
      console.error('Error updating review:', error);
    }
  };
 
  const handleOrderStatusChange = async (id: string, status: string) => {
    try {
      await fetch(`/api/admin/orders/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      await fetchOrders();
    } catch (error) {
      console.error('Error updating order:', error);
    }
  };
 
  const handleCategoryImageChange = (imageUrl: string) => {
    setCategoryImageForm(prev => ({
      ...prev,
      imageUrl,
    }));
  };
 
  const handleSaveCategoryImage = async () => {
    if (!categoryImageForm.categoryName || !categoryImageForm.imageUrl) {
      alert('Valitse kategoria ja lataa kuva');
      return;
    }
 
    try {
      const res = await fetch('/api/admin/category-images', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(categoryImageForm),
      });
 
      if (res.ok) {
        await fetchCategoryImages();
        setShowCategoryImageForm(false);
        setCategoryImageForm({ categoryName: '', imageUrl: '' });
        setEditingCategory('');
      }
    } catch (error) {
      console.error('Error saving category image:', error);
    }
  };
 
  const handleDeleteCategoryImage = async (categoryName: string) => {
    if (!confirm('Haluatko varmasti poistaa tämän kategorian kuvan?')) return;
 
    try {
      await fetch(`/api/admin/category-images/${encodeURIComponent(categoryName)}`, {
        method: 'DELETE',
      });
      await fetchCategoryImages();
    } catch (error) {
      console.error('Error deleting category image:', error);
    }
  };
 
  const handleEditCategoryImage = (categoryName: string, imageUrl: string) => {
    setEditingCategory(categoryName);
    setCategoryImageForm({ categoryName, imageUrl });
    setShowCategoryImageForm(true);
  };
 
  // Login screen
  Eif (status === 'unauthenticated') {
    return (
      <Section className="min-h-[50vh] flex items-center justify-center">
        <div className="w-full max-w-md bg-white p-8 rounded-2xl border border-gray-200 shadow-xl">
          <h2 className="text-2xl font-bold mb-6 text-center">Kirjaudu ylläpitoon</h2>
          {error && (
            <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-xl text-sm">
              {error}
            </div>
          )}
          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">Sähköposti</label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full p-3 border border-gray-200 rounded-xl focus:border-black transition-colors"
                placeholder="admin@varjoliitokauppa.fi"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-2">Salasana</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full p-3 border border-gray-200 rounded-xl focus:border-black transition-colors"
                placeholder="••••••••"
                required
              />
            </div>
            <button
              type="submit"
              className="w-full bg-black text-white py-3 rounded-xl shadow-md hover:shadow-lg transition-all"
            >
              Kirjaudu
            </button>
          </form>
          <div className="mt-4 text-center text-sm text-gray-500">
            <p>Testikäyttäjä: admin@varjoliitokauppa.fi / admin123</p>
          </div>
        </div>
      </Section>
    );
  }
 
  if (status === 'loading') {
    return (
      <Section className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-black mx-auto mb-4"></div>
          <p>Ladataan...</p>
        </div>
      </Section>
    );
  }
 
  const pendingReviews = reviews.filter(r => r.status === 'pending');
 
  return (
    <Section variant="white" className="min-h-screen">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-10">
        <h1 className="text-3xl font-bold">Hallintapaneeli</h1>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
          <div className="text-sm bg-gray-100 px-3 py-1 rounded-full border border-gray-200 break-all">
            {session?.user?.email}
          </div>
          <button
            onClick={() => signOut()}
            className="text-sm text-red-600 hover:text-red-700"
          >
            Kirjaudu ulos
          </button>
        </div>
      </div>
 
      {/* Tabs */}
      <div className="flex flex-wrap gap-2 sm:gap-4 mb-8 border-b border-gray-200">
        <button
          onClick={() => setActiveTab('products')}
          className={`pb-3 px-4 font-medium transition-colors ${
            activeTab === 'products'
              ? 'border-b-2 border-black text-black'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          Tuotteet ({products.length})
        </button>
        <button
          onClick={() => setActiveTab('reviews')}
          className={`pb-3 px-4 font-medium transition-colors ${
            activeTab === 'reviews'
              ? 'border-b-2 border-black text-black'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          Arvostelut ({pendingReviews.length} odottaa)
        </button>
        <button
          onClick={() => setActiveTab('orders')}
          className={`pb-3 px-4 font-medium transition-colors ${
            activeTab === 'orders'
              ? 'border-b-2 border-black text-black'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          Tilaukset ({orders.length})
        </button>
        <button
          onClick={() => setActiveTab('category-images')}
          className={`pb-3 px-4 font-medium transition-colors ${
            activeTab === 'category-images'
              ? 'border-b-2 border-black text-black'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          Kategorioiden kuvat
        </button>
      </div>
 
      {/* Products Tab */}
      {activeTab === 'products' && (
        <div>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
            <h2 className="text-2xl font-semibold">Tuotteet</h2>
            <button
              onClick={() => {
                setShowProductForm(true);
                setEditingProduct(null);
                setFormData({
                  name: '',
                  price: 0,
                  category: '',
                  subcategory: '',
                  shortDescription: '',
                  description: '',
                  images: [],
                  stock: 0,
                  brand: '',
                  isNew: false,
                  isUsed: false,
                });
              }}
              className="flex w-full sm:w-auto items-center justify-center gap-2 bg-black text-white px-4 py-2 rounded-xl hover:shadow-lg transition-all"
            >
              <PlusCircle size={20} />
              Lisää uusi tuote
            </button>
          </div>
 
          {/* Product Form Modal */}
          {showProductForm && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto p-6 sm:p-8">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
                  <h3 className="text-2xl font-bold">
                    {editingProduct ? 'Muokkaa tuotetta' : 'Lisää uusi tuote'}
                  </h3>
                  <button onClick={() => setShowProductForm(false)} className="text-gray-500 hover:text-black">
                    <X size={24} />
                  </button>
                </div>
 
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">Nimi</label>
                    <input
                      type="text"
                      value={formData.name ?? ''}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Hinta (€)</label>
                      <input
                        type="number"
                        value={formData.price ?? 0}
                        onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Alehinta (€)</label>
                      <input
                        type="number"
                        value={formData.salePrice ?? ''}
                        onChange={(e) => setFormData({ ...formData, salePrice: e.target.value ? parseFloat(e.target.value) : undefined })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Kategoria</label>
                      <select
                        value={formData.category ?? ''}
                        onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      >
                        <option value="">Valitse kategoria</option>
                        {CATEGORIES.map(cat => (
                          <option key={cat.name} value={cat.name}>{cat.name}</option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Alakategoria</label>
                      <select
                        value={formData.subcategory ?? ''}
                        onChange={(e) => setFormData({ ...formData, subcategory: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                        disabled={!formData.category}
                      >
                        <option value="">Valitse alakategoria</option>
                        {CATEGORIES.find(c => c.name === formData.category)?.subcategories?.map(sub => (
                          <option key={sub} value={sub}>{sub}</option>
                        ))}
                      </select>
                    </div>
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Lyhyt kuvaus</label>
                    <input
                      type="text"
                      value={formData.shortDescription ?? ''}
                      onChange={(e) => setFormData({ ...formData, shortDescription: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Kuvaus</label>
                    <textarea
                      value={formData.description ?? ''}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      rows={4}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                    />
                  </div>
 
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Varastosaldo</label>
                      <input
                        type="number"
                        value={formData.stock ?? 0}
                        onChange={(e) => setFormData({ ...formData, stock: parseInt(e.target.value) })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-2">Merkki</label>
                      <input
                        type="text"
                        value={formData.brand ?? ''}
                        onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  </div>
 
                  <div className="flex flex-col sm:flex-row gap-4">
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={formData.isNew}
                        onChange={(e) => setFormData({ ...formData, isNew: e.target.checked })}
                        className="rounded"
                      />
                      <span className="text-sm">Uutuus</span>
                    </label>
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={formData.isUsed}
                        onChange={(e) => setFormData({ ...formData, isUsed: e.target.checked })}
                        className="rounded"
                      />
                      <span className="text-sm">Käytetty</span>
                    </label>
                  </div>
 
                  {formData.isUsed && (
                    <div>
                      <label className="block text-sm font-medium mb-2">Kunto</label>
                      <input
                        type="text"
                        value={formData.condition ?? ''}
                        onChange={(e) => setFormData({ ...formData, condition: e.target.value })}
                        className="w-full p-3 border border-gray-200 rounded-xl"
                      />
                    </div>
                  )}
 
                  <ImageUpload
                    images={formData.images || []}
                    onImagesChange={handleImagesChange}
                    maxImages={10}
                  />
 
                  <div className="flex flex-col sm:flex-row gap-4 pt-4">
                    <button
                      onClick={handleSaveProduct}
                      className="flex-1 bg-black text-white py-3 rounded-xl hover:shadow-lg transition-all flex items-center justify-center gap-2"
                    >
                      <Save size={20} />
                      Tallenna
                    </button>
                    <button
                      onClick={() => setShowProductForm(false)}
                      className="flex-1 bg-gray-200 text-gray-700 py-3 rounded-xl hover:bg-gray-300 transition-all"
                    >
                      Peruuta
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
 
          {/* Products List */}
          <div className="grid gap-4">
            {products.map(product => (
              <div key={product.id} className="bg-white border border-gray-200 rounded-xl p-6 flex flex-col sm:flex-row gap-4">
                <div className="relative w-full sm:w-24 h-40 sm:h-24 overflow-hidden rounded-lg">
                  <Image
                    src={product.images[0] || '/placeholder.svg'}
                    alt={product.name}
                    fill
                    sizes="(max-width: 640px) 100vw, 96px"
                    className="object-cover"
                  />
                </div>
                <div className="flex-1">
                  <div className="flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-start">
                    <div>
                      <h3 className="font-semibold text-lg">{product.name}</h3>
                      <p className="text-gray-600 text-sm">{product.category} - {product.subcategory}</p>
                      <p className="text-sm mt-1">
                        <span className="font-medium">{product.price}€</span>
                        {product.salePrice && (
                          <span className="ml-2 text-red-600">{product.salePrice}€</span>
                        )}
                        <span className="ml-4 text-gray-500">Varasto: {product.stock} kpl</span>
                      </p>
                    </div>
                    <div className="flex flex-col sm:flex-row gap-2">
                      <button
                        onClick={() => handleEditProduct(product)}
                        className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      >
                        <Edit2 size={18} />
                      </button>
                      <button
                        onClick={() => handleDeleteProduct(product.id)}
                        className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
 
      {/* Reviews Tab */}
      {activeTab === 'reviews' && (
        <div>
          <h2 className="text-2xl font-semibold mb-6">Arvostelut ({pendingReviews.length} odottaa)</h2>
          <div className="space-y-4">
            {reviews.map(review => (
              <div key={review.id} className="bg-white border border-gray-200 rounded-xl p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-start mb-4">
                  <div>
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-medium">{review.author}</span>
                      <span className="text-yellow-500">{review.rating}/5 ⭐</span>
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                        review.status === 'approved' ? 'bg-green-100 text-green-700' :
                        review.status === 'rejected' ? 'bg-red-100 text-red-700' :
                        'bg-yellow-100 text-yellow-700'
                      }`}>
                        {review.status === 'approved' ? 'Hyväksytty' :
                         review.status === 'rejected' ? 'Hylätty' : 'Odottaa'}
                      </span>
                    </div>
                    <p className="text-sm text-gray-500 mt-1">{review.product?.name || 'Product not found'}</p>
                  </div>
                  {review.status === 'pending' && (
                    <div className="flex flex-col sm:flex-row gap-2">
                      <button
                        onClick={() => handleReviewAction(review.id, 'approved')}
                        className="w-full sm:w-auto px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors"
                      >
                        Hyväksy
                      </button>
                      <button
                        onClick={() => handleReviewAction(review.id, 'rejected')}
                        className="w-full sm:w-auto px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors"
                      >
                        Hylkää
                      </button>
                    </div>
                  )}
                </div>
                <p className="text-gray-700">{review.text}</p>
              </div>
            ))}
          </div>
        </div>
      )}
 
      {/* Orders Tab */}
      {activeTab === 'orders' && (
        <div>
          <h2 className="text-2xl font-semibold mb-6">Tilaukset</h2>
          <div className="space-y-4">
            {orders.map(order => (
              <div key={order.id} className="bg-white border border-gray-200 rounded-xl p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-start mb-4">
                  <div>
                    <h3 className="font-semibold text-lg">{order.customerName}</h3>
                    <p className="text-sm text-gray-600">{order.customerEmail} | {order.customerPhone}</p>
                    <p className="text-sm text-gray-600">{order.customerAddress}, {order.customerZip} {order.customerCity}</p>
                  </div>
                  <div className="w-full sm:w-auto text-left sm:text-right">
                    <p className="font-semibold text-lg">{order.total}€</p>
                    <select
                      value={order.status}
                      onChange={(e) => handleOrderStatusChange(order.id, e.target.value)}
                      className="mt-2 w-full sm:w-auto p-2 border border-gray-200 rounded-lg text-sm"
                    >
                      <option value="pending">Odottaa</option>
                      <option value="processing">Käsittelyssä</option>
                      <option value="shipped">Lähetetty</option>
                      <option value="delivered">Toimitettu</option>
                      <option value="cancelled">Peruutettu</option>
                    </select>
                  </div>
                </div>
                <div className="border-t border-gray-200 pt-4 mt-4">
                  <p className="text-sm font-medium mb-2">Tuotteet:</p>
                  {order.items?.map((item) => (
                    <div key={item.id} className="text-sm text-gray-600">
                      {item.product.name} - {item.quantity} kpl × {item.price}€
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
 
      {/* Category Images Tab */}
      {activeTab === 'category-images' && (
        <div>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
            <div>
              <h2 className="text-2xl font-semibold">Kategorioiden kuvat</h2>
              <p className="text-sm text-gray-600 mt-1">Hallitse etusivun &quot;Selaa tuoteryhmiä&quot; -osion kuvia</p>
            </div>
            <button
              onClick={() => {
                setShowCategoryImageForm(true);
                setEditingCategory('');
                setCategoryImageForm({ categoryName: '', imageUrl: '' });
              }}
              className="flex w-full sm:w-auto items-center justify-center gap-2 bg-black text-white px-4 py-2 rounded-xl hover:shadow-lg transition-all"
            >
              <PlusCircle size={20} />
              Lisää kategorian kuva
            </button>
          </div>
 
          {/* Category Image Form Modal */}
          {showCategoryImageForm && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6 sm:p-8">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
                  <h3 className="text-2xl font-bold">
                    {editingCategory ? 'Muokkaa kategorian kuvaa' : 'Lisää kategorian kuva'}
                  </h3>
                  <button onClick={() => setShowCategoryImageForm(false)} className="text-gray-500 hover:text-black">
                    <X size={24} />
                  </button>
                </div>
 
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">Kategoria</label>
                    <select
                      value={categoryImageForm.categoryName}
                      onChange={(e) => setCategoryImageForm({ ...categoryImageForm, categoryName: e.target.value })}
                      className="w-full p-3 border border-gray-200 rounded-xl"
                      disabled={!!editingCategory}
                    >
                      <option value="">Valitse kategoria</option>
                      {CATEGORIES.map(cat => (
                        <option key={cat.name} value={cat.name}>{cat.name}</option>
                      ))}
                    </select>
                    <p className="text-xs text-gray-500 mt-1">
                      Kategoriat tulevat CATEGORIES-vakiosta. Etusivulla näytetään 6 kategoriaa (MITTARIT ei näy).
                    </p>
                  </div>
 
                  <div>
                    <label className="block text-sm font-medium mb-2">Kuva</label>
                    <ImageUpload
                      images={categoryImageForm.imageUrl ? [categoryImageForm.imageUrl] : []}
                      onImagesChange={(images) => handleCategoryImageChange(images[0] || '')}
                      maxImages={1}
                    />
                  </div>
 
                  <div className="flex flex-col sm:flex-row gap-4 pt-4">
                    <button
                      onClick={handleSaveCategoryImage}
                      className="flex-1 bg-black text-white py-3 rounded-xl hover:shadow-lg transition-all flex items-center justify-center gap-2"
                    >
                      <Save size={20} />
                      Tallenna
                    </button>
                    <button
                      onClick={() => setShowCategoryImageForm(false)}
                      className="flex-1 bg-gray-200 text-gray-700 py-3 rounded-xl hover:bg-gray-300 transition-all"
                    >
                      Peruuta
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
 
          {/* Category Images Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {CATEGORIES.filter(cat => cat.name !== "MITTARIT").slice(0, 6).map(cat => {
              const existingImage = categoryImages.find(img => img.categoryName === cat.name);
              const defaultImage = CATEGORY_IMAGE_DEFAULTS[cat.name];
              const isPicsum = existingImage?.imageUrl?.includes('picsum.photos');
              const customImage = !isPicsum ? existingImage?.imageUrl : undefined;
              const hasImage = Boolean(customImage || defaultImage);
              const displayImage = customImage || defaultImage || '/placeholder.svg';
              return (
                <div key={cat.name} className="bg-white border border-gray-200 rounded-xl overflow-hidden">
                  <div className="relative h-48 bg-gray-100">
                    <Image
                      src={displayImage}
                      alt={cat.name}
                      fill
                      sizes="(max-width: 768px) 100vw, 33vw"
                      className="object-cover"
                    />
                    {!hasImage && (
                      <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                        <span className="text-white text-sm font-medium">Placeholder-kuva</span>
                      </div>
                    )}
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-lg mb-2">{cat.name}</h3>
                    <p className="text-sm text-gray-600 mb-4">
                      {cat.subcategories?.length || 0} alakategoriaa
                    </p>
                    <div className="flex gap-2">
                      {customImage ? (
                        <>
                          <button
                            onClick={() => handleEditCategoryImage(cat.name, customImage)}
                            className="flex-1 w-full sm:w-auto px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm font-medium"
                          >
                            Muokkaa
                          </button>
                          <button
                            onClick={() => handleDeleteCategoryImage(cat.name)}
                            className="flex-1 w-full sm:w-auto px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors text-sm font-medium"
                          >
                            Poista
                          </button>
                        </>
                      ) : hasImage ? (
                        <button
                          onClick={() => handleEditCategoryImage(cat.name, defaultImage || '')}
                          className="flex-1 w-full sm:w-auto px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm font-medium"
                        >
                          Muokkaa
                        </button>
                      ) : (
                        <button
                          onClick={() => {
                            setCategoryImageForm({ categoryName: cat.name, imageUrl: '' });
                            setShowCategoryImageForm(true);
                          }}
                          className="flex-1 w-full sm:w-auto px-4 py-2 bg-black text-white rounded-lg hover:shadow-lg transition-all text-sm font-medium"
                        >
                          Lisää kuva
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </Section>
  );
};
 
export default Admin;