import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { cancellationPeriodApi } 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 } from 'lucide-react';
import { Link } from 'react-router-dom';
import type { CancellationPeriod } from '../../types';

export default function CancellationPeriodList() {
  const [showModal, setShowModal] = useState(false);
  const [editingPeriod, setEditingPeriod] = useState<CancellationPeriod | null>(null);
  const [showInactive, setShowInactive] = useState(false);
  const { hasPermission } = useAuth();
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['cancellation-periods', showInactive],
    queryFn: () => cancellationPeriodApi.getAll(showInactive),
  });

  const deleteMutation = useMutation({
    mutationFn: cancellationPeriodApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cancellation-periods'] });
    },
  });

  const handleEdit = (period: CancellationPeriod) => {
    setEditingPeriod(period);
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
    setEditingPeriod(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">Kündigungsfristen</h1>
        {hasPermission('platforms:create') && (
          <Button onClick={() => setShowModal(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Neue Frist
          </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>

        <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm">
          <strong>Code-Format:</strong> Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)
          <br />
          <strong>Beispiele:</strong> 14T = 14 Tage, 3M = 3 Monate, 1J = 1 Jahr
        </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">Code</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Beschreibung</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((period) => (
                  <tr key={period.id} className="border-b hover:bg-gray-50">
                    <td className="py-3 px-4 font-mono font-medium">{period.code}</td>
                    <td className="py-3 px-4">{period.description}</td>
                    <td className="py-3 px-4">
                      <Badge variant={period.isActive ? 'success' : 'danger'}>
                        {period.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(period)}>
                            <Edit className="w-4 h-4" />
                          </Button>
                        )}
                        {hasPermission('platforms:delete') && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm('Kündigungsfrist wirklich löschen?')) {
                                deleteMutation.mutate(period.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 Kündigungsfristen vorhanden.</div>
        )}
      </Card>

      <CancellationPeriodModal
        isOpen={showModal}
        onClose={handleClose}
        period={editingPeriod}
      />
    </div>
  );
}

function CancellationPeriodModal({
  isOpen,
  onClose,
  period,
}: {
  isOpen: boolean;
  onClose: () => void;
  period: CancellationPeriod | null;
}) {
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState({
    code: '',
    description: '',
    isActive: true,
  });

  // Reset form when modal opens or period changes
  useEffect(() => {
    if (isOpen) {
      if (period) {
        setFormData({
          code: period.code,
          description: period.description,
          isActive: period.isActive,
        });
      } else {
        setFormData({ code: '', description: '', isActive: true });
      }
    }
  }, [isOpen, period]);

  const createMutation = useMutation({
    mutationFn: cancellationPeriodApi.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cancellation-periods'] });
      onClose();
      setFormData({ code: '', description: '', isActive: true });
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: Partial<CancellationPeriod>) =>
      cancellationPeriodApi.update(period!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cancellation-periods'] });
      onClose();
    },
  });

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

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

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={period ? 'Kündigungsfrist bearbeiten' : 'Neue Kündigungsfrist'}
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <Input
          label="Code *"
          value={formData.code}
          onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase() })}
          required
          placeholder="z.B. 14T, 3M, 1J"
        />

        <Input
          label="Beschreibung *"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          required
          placeholder="z.B. 14 Tage, 3 Monate, 1 Jahr"
        />

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