import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Hash } from 'lucide-react';
import toast from 'react-hot-toast';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import { creditNoteApi } from '../../services/api';
import type { CreditNoteNumberRange } from '../../types';
import { useAuth } from '../../context/AuthContext';

interface RangeEditorProps {
  title: string;
  description: string;
  queryKey: string;
  load: () => Promise<{ data?: CreditNoteNumberRange }>;
  save: (payload: Partial<CreditNoteNumberRange>) => Promise<unknown>;
  defaultPrefix: string;
  canEdit: boolean;
}

function RangeEditor({ title, description, queryKey, load, save, defaultPrefix, canEdit }: RangeEditorProps) {
  const queryClient = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: [queryKey], queryFn: load });
  const range = data?.data;

  const [prefix, setPrefix] = useState(defaultPrefix);
  const [includeYear, setIncludeYear] = useState(true);
  const [separator, setSeparator] = useState('-');
  const [padding, setPadding] = useState(4);
  const [nextNumber, setNextNumber] = useState(1);
  const [resetYearly, setResetYearly] = useState(true);

  useEffect(() => {
    if (range) {
      setPrefix(range.prefix);
      setIncludeYear(range.includeYear);
      setSeparator(range.separator);
      setPadding(range.padding);
      setNextNumber(range.nextNumber);
      setResetYearly(range.resetYearly);
    }
  }, [range]);

  const saveMutation = useMutation({
    mutationFn: () => save({ prefix, includeYear, separator, padding, nextNumber, resetYearly }),
    onSuccess: () => {
      toast.success('Nummernkreis gespeichert');
      queryClient.invalidateQueries({ queryKey: [queryKey] });
    },
    onError: (err: Error) => toast.error(err.message || 'Speichern fehlgeschlagen'),
  });

  const year = new Date().getFullYear();
  const previewValue = resetYearly && range && range.currentYear !== year ? 1 : nextNumber;
  const preview = `${prefix}${includeYear ? `${year}${separator}` : ''}${String(previewValue).padStart(padding, '0')}`;

  return (
    <div className="bg-white rounded-lg shadow p-6 space-y-4">
      <div>
        <h2 className="font-semibold text-gray-800">{title}</h2>
        <p className="text-sm text-gray-500">{description}</p>
      </div>

      {isLoading ? (
        <div className="text-gray-500 text-sm">Laden …</div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input label="Präfix" value={prefix} onChange={(e) => setPrefix(e.target.value)} disabled={!canEdit} placeholder={defaultPrefix} />
            <Input label="Trennzeichen (vor der Nummer)" value={separator} onChange={(e) => setSeparator(e.target.value)} disabled={!canEdit} placeholder="-" />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label="Stellen (Nullen auffüllen)"
              type="number"
              min={1}
              max={10}
              value={padding}
              onChange={(e) => setPadding(Math.min(Math.max(parseInt(e.target.value) || 1, 1), 10))}
              disabled={!canEdit}
            />
            <Input
              label="Nächste Nummer"
              type="number"
              min={1}
              value={nextNumber}
              onChange={(e) => setNextNumber(Math.max(parseInt(e.target.value) || 1, 1))}
              disabled={!canEdit}
            />
          </div>

          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={includeYear} onChange={(e) => setIncludeYear(e.target.checked)} disabled={!canEdit} className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" />
            Jahr in die Nummer aufnehmen (z.B. {prefix}{year}{separator}0001)
          </label>

          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={resetYearly} onChange={(e) => setResetYearly(e.target.checked)} disabled={!canEdit} className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" />
            Zähler zum Jahreswechsel auf 1 zurücksetzen
          </label>

          <div className="rounded-lg bg-blue-50 border border-blue-200 px-3 py-2 text-sm">
            Nächste Nummer: <span className="font-mono font-semibold">{preview}</span>
          </div>

          {canEdit && (
            <div className="flex justify-end">
              <Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
                {saveMutation.isPending ? 'Speichern …' : 'Speichern'}
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

export default function CreditNoteNumberRange() {
  const { hasPermission } = useAuth();
  const canEdit = hasPermission('settings:update');

  return (
    <div className="max-w-2xl">
      <Link to="/settings" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
        <ArrowLeft className="w-4 h-4" /> Einstellungen
      </Link>
      <h1 className="text-2xl font-bold flex items-center gap-2 mb-1">
        <Hash className="w-6 h-6 text-blue-600" /> Nummernkreise: Gutschrift & Lieferschein
      </h1>
      <p className="text-gray-500 mb-6">
        Getrennte fortlaufende Nummerierung für echte Gutschriften und für Lieferscheine
        (betragslose Sachwert-Übergaben).
      </p>

      <div className="space-y-6">
        <RangeEditor
          title="Gutschrift-Nummernkreis"
          description="Für Geld-Gutschriften und Sachwerte mit Betrag."
          queryKey="credit-note-number-range"
          load={() => creditNoteApi.getNumberRange()}
          save={(p) => creditNoteApi.updateNumberRange(p)}
          defaultPrefix="GS-"
          canEdit={canEdit}
        />
        <RangeEditor
          title="Lieferschein-Nummernkreis"
          description="Für betragslose Sachwert-Übergaben (keine Rechnung/Gutschrift)."
          queryKey="delivery-note-number-range"
          load={() => creditNoteApi.getDeliveryNoteNumberRange()}
          save={(p) => creditNoteApi.updateDeliveryNoteNumberRange(p)}
          defaultPrefix="LS-"
          canEdit={canEdit}
        />
      </div>
    </div>
  );
}
