import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { contractCategoryApi } from '../../services/api';
import { useAuth } from '../../context/AuthContext';
import Card from '../../components/ui/Card';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import Modal from '../../components/ui/Modal';
import Badge from '../../components/ui/Badge';
import { Plus, Edit, Trash2, ArrowLeft, GripVertical, Zap, Flame, Wifi, Cable, Smartphone, Tv, Car, FileText, Network } from 'lucide-react';
import { Link } from 'react-router-dom';
import type { ContractCategory } from '../../types';

// Icon-Mapping für die Anzeige
const iconMap: Record<string, React.ReactNode> = {
  Zap: <Zap className="w-5 h-5" />,
  Flame: <Flame className="w-5 h-5" />,
  Wifi: <Wifi className="w-5 h-5" />,
  Cable: <Cable className="w-5 h-5" />,
  Network: <Network className="w-5 h-5" />,
  Smartphone: <Smartphone className="w-5 h-5" />,
  Tv: <Tv className="w-5 h-5" />,
  Car: <Car className="w-5 h-5" />,
  FileText: <FileText className="w-5 h-5" />,
};

const availableIcons = [
  { value: 'Zap', label: 'Blitz (Strom)' },
  { value: 'Flame', label: 'Flamme (Gas)' },
  { value: 'Wifi', label: 'WLAN (DSL)' },
  { value: 'Cable', label: 'Kabel' },
  { value: 'Network', label: 'Netzwerk (Glasfaser)' },
  { value: 'Smartphone', label: 'Smartphone (Mobilfunk)' },
  { value: 'Tv', label: 'TV' },
  { value: 'Car', label: 'Auto (KFZ)' },
  { value: 'FileText', label: 'Dokument (Sonstige)' },
];

const availableColors = [
  { value: '#FFC107', label: 'Gelb' },
  { value: '#FF5722', label: 'Orange' },
  { value: '#2196F3', label: 'Blau' },
  { value: '#9C27B0', label: 'Lila' },
  { value: '#4CAF50', label: 'Grün' },
  { value: '#E91E63', label: 'Pink' },
  { value: '#607D8B', label: 'Grau' },
  { value: '#795548', label: 'Braun' },
  { value: '#00BCD4', label: 'Cyan' },
  { value: '#F44336', label: 'Rot' },
];

export default function ContractCategoryList() {
  const [showModal, setShowModal] = useState(false);
  const [editingCategory, setEditingCategory] = useState<ContractCategory | null>(null);
  const [showInactive, setShowInactive] = useState(false);
  const { hasPermission } = useAuth();
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['contract-categories', showInactive],
    queryFn: () => contractCategoryApi.getAll(showInactive),
  });

  const deleteMutation = useMutation({
    mutationFn: contractCategoryApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contract-categories'] });
    },
    onError: (error: Error) => {
      alert(error.message);
    },
  });

  const handleEdit = (category: ContractCategory) => {
    setEditingCategory(category);
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
    setEditingCategory(null);
  };

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <Link to="/settings">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="w-4 h-4" />
          </Button>
        </Link>
        <h1 className="text-2xl font-bold flex-1">Vertragstypen</h1>
        {hasPermission('developer:access') && (
          <Button onClick={() => setShowModal(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Neuer Vertragstyp
          </Button>
        )}
      </div>

      <Card>
        <div className="mb-4">
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={showInactive}
              onChange={(e) => setShowInactive(e.target.checked)}
              className="rounded"
            />
            Inaktive anzeigen
          </label>
        </div>

        {isLoading ? (
          <div className="text-center py-8 text-gray-500">Laden...</div>
        ) : data?.data && data.data.length > 0 ? (
          <div className="space-y-2">
            {data.data.map((category) => (
              <div
                key={category.id}
                className="flex items-center p-4 border rounded-lg hover:bg-gray-50"
              >
                <div className="mr-3 text-gray-400">
                  <GripVertical className="w-5 h-5" />
                </div>
                <div
                  className="w-10 h-10 rounded-lg flex items-center justify-center mr-4"
                  style={{ backgroundColor: category.color || '#E5E7EB', color: '#fff' }}
                >
                  {category.icon && iconMap[category.icon] ? iconMap[category.icon] : <FileText className="w-5 h-5" />}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-medium">{category.name}</span>
                    <Badge variant={category.isActive ? 'success' : 'danger'}>
                      {category.isActive ? 'Aktiv' : 'Inaktiv'}
                    </Badge>
                    <span className="text-sm text-gray-500">
                      ({category._count?.contracts || 0} Verträge)
                    </span>
                  </div>
                  <div className="text-sm text-gray-500">
                    Code: <span className="font-mono">{category.code}</span>
                  </div>
                </div>
                <div className="flex gap-2 ml-4">
                  {hasPermission('developer:access') && (
                    <Button variant="ghost" size="sm" onClick={() => handleEdit(category)} title="Bearbeiten">
                      <Edit className="w-4 h-4" />
                    </Button>
                  )}
                  {hasPermission('developer:access') && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        if (confirm('Vertragstyp wirklich löschen?')) {
                          deleteMutation.mutate(category.id);
                        }
                      }}
                      title="Löschen"
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">Keine Vertragstypen vorhanden.</div>
        )}
      </Card>

      <ContractCategoryModal
        isOpen={showModal}
        onClose={handleClose}
        category={editingCategory}
      />
    </div>
  );
}

function ContractCategoryModal({
  isOpen,
  onClose,
  category,
}: {
  isOpen: boolean;
  onClose: () => void;
  category: ContractCategory | null;
}) {
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState({
    code: '',
    name: '',
    icon: 'FileText',
    color: '#607D8B',
    sortOrder: 0,
    isActive: true,
  });

  useEffect(() => {
    if (isOpen) {
      if (category) {
        setFormData({
          code: category.code,
          name: category.name,
          icon: category.icon || 'FileText',
          color: category.color || '#607D8B',
          sortOrder: category.sortOrder,
          isActive: category.isActive,
        });
      } else {
        setFormData({
          code: '',
          name: '',
          icon: 'FileText',
          color: '#607D8B',
          sortOrder: 0,
          isActive: true,
        });
      }
    }
  }, [isOpen, category]);

  const createMutation = useMutation({
    mutationFn: contractCategoryApi.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contract-categories'] });
      onClose();
    },
    onError: (error: Error) => {
      alert(error.message);
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: Partial<ContractCategory>) =>
      contractCategoryApi.update(category!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contract-categories'] });
      onClose();
    },
    onError: (error: Error) => {
      alert(error.message);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (category) {
      updateMutation.mutate(formData);
    } else {
      createMutation.mutate(formData);
    }
  };

  const isLoading = createMutation.isPending || updateMutation.isPending;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={category ? 'Vertragstyp bearbeiten' : 'Neuer Vertragstyp'}
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <Input
          label="Code (technisch) *"
          value={formData.code}
          onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '') })}
          required
          placeholder="z.B. ELECTRICITY, MOBILE_BUSINESS"
          disabled={!!category} // Code nicht änderbar bei Bearbeitung
        />

        <Input
          label="Anzeigename *"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          required
          placeholder="z.B. Strom, Mobilfunk Business"
        />

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Icon</label>
          <div className="grid grid-cols-4 gap-2">
            {availableIcons.map((icon) => (
              <button
                key={icon.value}
                type="button"
                onClick={() => setFormData({ ...formData, icon: icon.value })}
                className={`p-3 border rounded-lg flex flex-col items-center gap-1 text-xs ${
                  formData.icon === icon.value ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:bg-gray-50'
                }`}
              >
                {iconMap[icon.value]}
                <span className="truncate w-full text-center">{icon.label.split(' ')[0]}</span>
              </button>
            ))}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Farbe</label>
          <div className="flex flex-wrap gap-2">
            {availableColors.map((color) => (
              <button
                key={color.value}
                type="button"
                onClick={() => setFormData({ ...formData, color: color.value })}
                className={`w-8 h-8 rounded-full border-2 ${
                  formData.color === color.value ? 'border-gray-800 ring-2 ring-offset-2 ring-gray-400' : 'border-transparent'
                }`}
                style={{ backgroundColor: color.value }}
                title={color.label}
              />
            ))}
          </div>
        </div>

        <Input
          label="Sortierung"
          type="number"
          value={formData.sortOrder}
          onChange={(e) => setFormData({ ...formData, sortOrder: parseInt(e.target.value) || 0 })}
          placeholder="0"
        />

        {category && (
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={formData.isActive}
              onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
              className="rounded"
            />
            Aktiv
          </label>
        )}

        <div className="flex justify-end gap-2">
          <Button type="button" variant="secondary" onClick={onClose}>
            Abbrechen
          </Button>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? 'Speichern...' : 'Speichern'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
