import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { platformApi } 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 } from 'lucide-react';
import type { SalesPlatform } from '../../types';

export default function PlatformList() {
  const [showModal, setShowModal] = useState(false);
  const [editingPlatform, setEditingPlatform] = useState<SalesPlatform | null>(null);
  const [showInactive, setShowInactive] = useState(false);
  const { hasPermission } = useAuth();
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['platforms', showInactive],
    queryFn: () => platformApi.getAll(showInactive),
  });

  const deleteMutation = useMutation({
    mutationFn: platformApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['platforms'] });
    },
  });

  const handleEdit = (platform: SalesPlatform) => {
    setEditingPlatform(platform);
    setShowModal(true);
  };

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Vertriebsplattformen</h1>
        {hasPermission('platforms:create') && (
          <Button onClick={() => setShowModal(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Neue Plattform
          </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="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Name</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Kontakt</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th>
                  <th className="text-right py-3 px-4 font-medium text-gray-600">Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {data.data.map((platform) => (
                  <tr key={platform.id} className="border-b hover:bg-gray-50">
                    <td className="py-3 px-4 font-medium">{platform.name}</td>
                    <td className="py-3 px-4 text-gray-500">{platform.contactInfo || '-'}</td>
                    <td className="py-3 px-4">
                      <Badge variant={platform.isActive ? 'success' : 'danger'}>
                        {platform.isActive ? 'Aktiv' : 'Inaktiv'}
                      </Badge>
                    </td>
                    <td className="py-3 px-4 text-right">
                      <div className="flex justify-end gap-2">
                        {hasPermission('platforms:update') && (
                          <Button variant="ghost" size="sm" onClick={() => handleEdit(platform)}>
                            <Edit className="w-4 h-4" />
                          </Button>
                        )}
                        {hasPermission('platforms:delete') && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm('Plattform wirklich löschen?')) {
                                deleteMutation.mutate(platform.id);
                              }
                            }}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">Keine Plattformen vorhanden.</div>
        )}
      </Card>

      <PlatformModal
        isOpen={showModal}
        onClose={handleClose}
        platform={editingPlatform}
      />
    </div>
  );
}

function PlatformModal({
  isOpen,
  onClose,
  platform,
}: {
  isOpen: boolean;
  onClose: () => void;
  platform: SalesPlatform | null;
}) {
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState({
    name: '',
    contactInfo: '',
    isActive: true,
  });

  useState(() => {
    if (platform) {
      setFormData({
        name: platform.name,
        contactInfo: platform.contactInfo || '',
        isActive: platform.isActive,
      });
    } else {
      setFormData({ name: '', contactInfo: '', isActive: true });
    }
  });

  // Reset form when platform changes
  if (platform && formData.name !== platform.name) {
    setFormData({
      name: platform.name,
      contactInfo: platform.contactInfo || '',
      isActive: platform.isActive,
    });
  } else if (!platform && formData.name !== '') {
    // Only reset if we're opening for new (not editing)
  }

  const createMutation = useMutation({
    mutationFn: platformApi.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['platforms'] });
      onClose();
      setFormData({ name: '', contactInfo: '', isActive: true });
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: Partial<SalesPlatform>) =>
      platformApi.update(platform!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['platforms'] });
      onClose();
    },
  });

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

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

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={platform ? 'Plattform bearbeiten' : 'Neue Plattform'}
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <Input
          label="Name *"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          required
        />

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Kontaktinformationen
          </label>
          <textarea
            value={formData.contactInfo}
            onChange={(e) => setFormData({ ...formData, contactInfo: e.target.value })}
            rows={3}
            className="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="E-Mail, Telefon, Ansprechpartner..."
          />
        </div>

        {platform && (
          <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>
  );
}
