import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Prize, getPrizes, savePrizes } from '@/lib/prizes';
import { Trash2, Edit, Plus } from 'lucide-react';

export default function AdminPanel() {
  const [prizes, setPrizes] = useState<Prize[]>([]);
  const [editingPrize, setEditingPrize] = useState<Prize | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    color: '#dc2626',
    probability: 10
  });

  useEffect(() => {
    setPrizes(getPrizes());
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingPrize) {
      // Update existing prize
      const updatedPrizes = prizes.map(prize =>
        prize.id === editingPrize.id
          ? { ...prize, ...formData }
          : prize
      );
      setPrizes(updatedPrizes);
      savePrizes(updatedPrizes);
      setEditingPrize(null);
    } else {
      // Add new prize
      const newPrize: Prize = {
        id: Date.now().toString(),
        ...formData
      };
      const updatedPrizes = [...prizes, newPrize];
      setPrizes(updatedPrizes);
      savePrizes(updatedPrizes);
    }

    setFormData({ name: '', color: '#dc2626', probability: 10 });
  };

  const handleEdit = (prize: Prize) => {
    setEditingPrize(prize);
    setFormData({
      name: prize.name,
      color: prize.color,
      probability: prize.probability
    });
  };

  const handleDelete = (id: string) => {
    const updatedPrizes = prizes.filter(prize => prize.id !== id);
    setPrizes(updatedPrizes);
    savePrizes(updatedPrizes);
  };

  const cancelEdit = () => {
    setEditingPrize(null);
    setFormData({ name: '', color: '#dc2626', probability: 10 });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-red-900 via-red-800 to-red-900 p-6">
      <div className="max-w-6xl mx-auto space-y-6">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-yellow-400 mb-2">Admin Panel</h1>
          <p className="text-red-200">Kelola Hadiah Lucky Spin</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Form */}
          <Card className="bg-red-800/50 border-yellow-400">
            <CardHeader>
              <CardTitle className="text-yellow-400">
                {editingPrize ? 'Edit Hadiah' : 'Tambah Hadiah Baru'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <Label htmlFor="name" className="text-red-100">Nama Hadiah</Label>
                  <Input
                    id="name"
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="bg-red-700/50 border-red-600 text-white"
                    placeholder="Contoh: 100.000, ZONK"
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="color" className="text-red-100">Warna</Label>
                  <div className="flex gap-2">
                    <Input
                      id="color"
                      type="color"
                      value={formData.color}
                      onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                      className="w-16 h-10 bg-red-700/50 border-red-600"
                    />
                    <Input
                      type="text"
                      value={formData.color}
                      onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                      className="bg-red-700/50 border-red-600 text-white"
                      placeholder="#dc2626"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="probability" className="text-red-100">Probabilitas (%)</Label>
                  <Input
                    id="probability"
                    type="number"
                    min="1"
                    max="100"
                    value={formData.probability}
                    onChange={(e) => setFormData({ ...formData, probability: parseInt(e.target.value) })}
                    className="bg-red-700/50 border-red-600 text-white"
                    required
                  />
                </div>

                <div className="flex gap-2">
                  <Button type="submit" className="bg-yellow-600 hover:bg-yellow-700 text-red-900">
                    <Plus className="w-4 h-4 mr-2" />
                    {editingPrize ? 'Update' : 'Tambah'}
                  </Button>
                  {editingPrize && (
                    <Button type="button" variant="outline" onClick={cancelEdit} className="border-red-400 text-red-100">
                      Batal
                    </Button>
                  )}
                </div>
              </form>
            </CardContent>
          </Card>

          {/* Prize List */}
          <Card className="bg-red-800/50 border-yellow-400">
            <CardHeader>
              <CardTitle className="text-yellow-400">Daftar Hadiah</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow className="border-red-600">
                    <TableHead className="text-red-100">Nama</TableHead>
                    <TableHead className="text-red-100">Warna</TableHead>
                    <TableHead className="text-red-100">Probabilitas</TableHead>
                    <TableHead className="text-red-100">Aksi</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {prizes.map((prize) => (
                    <TableRow key={prize.id} className="border-red-600">
                      <TableCell className="text-white font-medium">{prize.name}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div 
                            className="w-6 h-6 rounded border border-red-400"
                            style={{ backgroundColor: prize.color }}
                          ></div>
                          <span className="text-red-100 text-sm">{prize.color}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-white">{prize.probability}%</TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleEdit(prize)}
                            className="border-yellow-400 text-yellow-400 hover:bg-yellow-400 hover:text-red-900"
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleDelete(prize.id)}
                            className="border-red-400 text-red-400 hover:bg-red-400 hover:text-white"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </div>

        <div className="text-center">
          <Button 
            onClick={() => window.location.href = '/'}
            className="bg-yellow-600 hover:bg-yellow-700 text-red-900"
          >
            Kembali ke Lucky Spin
          </Button>
        </div>
      </div>
    </div>
  );
}