import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { contractDurationApi } 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 { ContractDuration } from '../../types';

export default function ContractDurationList() {
  const [showModal, setShowModal] = useState(false);
  const [editingDuration, setEditingDuration] = useState<ContractDuration | null>(null);
  const [showInactive, setShowInactive] = useState(false);
  const { hasPermission } = useAuth();
  const queryClient = useQueryClient();

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

  const deleteMutation = useMutation({
    mutationFn: contractDurationApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contract-durations'] });
    },
  });

  const handleEdit = (duration: ContractDuration) => {
    setEditingDuration(duration);
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
    setEditingDuration(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">Vertragslaufzeiten</h1>
        {hasPermission('platforms:create') && (
          <Button onClick={() => setShowModal(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Neue Laufzeit
          </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> 12M = 12 Monate, 24M = 24 Monate, 2J = 2 Jahre
        </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((duration) => (
                  <tr key={duration.id} className="border-b hover:bg-gray-50">
                    <td className="py-3 px-4 font-mono font-medium">{duration.code}</td>
                    <td className="py-3 px-4">{duration.description}</td>
                    <td className="py-3 px-4">
                      <Badge variant={duration.isActive ? 'success' : 'danger'}>
                        {duration.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(duration)}>
                            <Edit className="w-4 h-4" />
                          </Button>
                        )}
                        {hasPermission('platforms:delete') && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              if (confirm('Laufzeit wirklich löschen?')) {
                                deleteMutation.mutate(duration.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 Laufzeiten vorhanden.</div>
        )}
      </Card>

      <ContractDurationModal
        isOpen={showModal}
        onClose={handleClose}
        duration={editingDuration}
      />
    </div>
  );
}

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

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

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

  const updateMutation = useMutation({
    mutationFn: (data: Partial<ContractDuration>) =>
      contractDurationApi.update(duration!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contract-durations'] });
      onClose();
    },
  });

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

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

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={duration ? 'Laufzeit bearbeiten' : 'Neue Laufzeit'}
    >
      <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. 12M, 24M, 2J"
        />

        <Input
          label="Beschreibung *"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          required
          placeholder="z.B. 12 Monate, 24 Monate, 2 Jahre"
        />

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