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

type Form = Omit<CompanyProfile, 'id' | 'logoPath'>;

const EMPTY: Form = {
  name: '', street: '', houseNumber: '', postalCode: '', city: '', country: 'DE',
  vatId: '', taxNumber: '', commercialRegister: '', managingDirector: '',
  email: '', phone: '', website: '', iban: '', bic: '', bankName: '',
};

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

  const { data, isLoading } = useQuery({
    queryKey: ['company-profile'],
    queryFn: () => companyProfileApi.get(),
  });

  const [form, setForm] = useState<Form>(EMPTY);
  const set = <K extends keyof Form>(k: K, v: Form[K]) => setForm((f) => ({ ...f, [k]: v }));

  useEffect(() => {
    if (data?.data) {
      const { id, logoPath, ...rest } = data.data;
      void id; void logoPath;
      setForm({ ...EMPTY, ...rest });
    }
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: () => companyProfileApi.update(form),
    onSuccess: () => {
      toast.success('Firmendaten gespeichert');
      queryClient.invalidateQueries({ queryKey: ['company-profile'] });
    },
    onError: (err: Error) => toast.error(err.message || 'Speichern fehlgeschlagen'),
  });

  if (isLoading) return <div className="p-6 text-gray-500">Laden …</div>;

  const field = (label: string, key: keyof Form, placeholder?: string) => (
    <Input label={label} value={form[key]} onChange={(e) => set(key, e.target.value)} disabled={!canEdit} placeholder={placeholder} />
  );

  return (
    <div className="max-w-3xl">
      <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">
        <Building2 className="w-6 h-6 text-blue-600" /> Firmenstammdaten (Absender)
      </h1>
      <p className="text-gray-500 mb-6">
        Diese Daten erscheinen als Absender auf Gutschrift-PDFs und in der ZUGFeRD-E-Rechnung.
      </p>

      <div className="space-y-6">
        <div className="bg-white rounded-lg shadow p-6 space-y-4">
          <h2 className="font-semibold text-gray-800">Firma & Anschrift</h2>
          {field('Firmenname', 'name', 'z.B. Hacker-Net Telekommunikation')}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="md:col-span-2">{field('Straße', 'street')}</div>
            {field('Hausnummer', 'houseNumber')}
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {field('PLZ', 'postalCode')}
            <div className="md:col-span-1">{field('Ort', 'city')}</div>
            {field('Land (ISO-2)', 'country', 'DE')}
          </div>
          {field('Geschäftsführer/Inhaber', 'managingDirector')}
        </div>

        <div className="bg-white rounded-lg shadow p-6 space-y-4">
          <h2 className="font-semibold text-gray-800">Steuer & Register</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {field('USt-IdNr', 'vatId', 'DE123456789')}
            {field('Steuernummer', 'taxNumber')}
          </div>
          {field('Handelsregister', 'commercialRegister', 'z.B. HRB 12345, Amtsgericht Oldenburg')}
          <p className="text-xs text-gray-500">
            Für ZUGFeRD an Firmenkunden mit USt ist die USt-IdNr erforderlich.
          </p>
        </div>

        <div className="bg-white rounded-lg shadow p-6 space-y-4">
          <h2 className="font-semibold text-gray-800">Kontakt & Bank</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {field('E-Mail', 'email')}
            {field('Telefon', 'phone')}
          </div>
          {field('Website', 'website')}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {field('IBAN', 'iban')}
            {field('BIC', 'bic')}
            {field('Bank', 'bankName')}
          </div>
        </div>

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