import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { customerApi } 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 Badge from '../../components/ui/Badge';
import { Plus, Search, Eye, Edit } from 'lucide-react';

export default function CustomerList() {
  const [search, setSearch] = useState('');
  const [type, setType] = useState('');
  const [page, setPage] = useState(1);
  const { hasPermission } = useAuth();

  const { data, isLoading } = useQuery({
    queryKey: ['customers', search, type, page],
    queryFn: () => customerApi.getAll({ search, type: type || undefined, page, limit: 20 }),
  });

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Kunden</h1>
        {hasPermission('customers:create') && (
          <Link to="/customers/new">
            <Button>
              <Plus className="w-4 h-4 mr-2" />
              Neuer Kunde
            </Button>
          </Link>
        )}
      </div>

      <Card className="mb-6">
        <div className="flex gap-2 items-center">
          <Input
            placeholder="Suchen..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="flex-1"
          />
          <select
            value={type}
            onChange={(e) => setType(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg w-28 flex-shrink-0"
          >
            <option value="">Alle</option>
            <option value="PRIVATE">Privat</option>
            <option value="BUSINESS">Firma</option>
          </select>
          <Button variant="secondary" className="flex-shrink-0">
            <Search className="w-4 h-4" />
          </Button>
        </div>
      </Card>

      <Card>
        {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">Kundennr.</th>
                    <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">Typ</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600">E-Mail</th>
                    <th className="text-left py-3 px-4 font-medium text-gray-600">Verträge</th>
                    <th className="text-right py-3 px-4 font-medium text-gray-600">Aktionen</th>
                  </tr>
                </thead>
                <tbody>
                  {data.data.map((customer) => (
                    <tr key={customer.id} className="border-b hover:bg-gray-50">
                      <td className="py-3 px-4 font-mono text-sm">{customer.customerNumber}</td>
                      <td className="py-3 px-4">
                        {customer.type === 'BUSINESS' && customer.companyName
                          ? customer.companyName
                          : `${customer.firstName} ${customer.lastName}`}
                      </td>
                      <td className="py-3 px-4">
                        <Badge variant={customer.type === 'BUSINESS' ? 'info' : 'default'}>
                          {customer.type === 'BUSINESS' ? 'Firma' : 'Privat'}
                        </Badge>
                      </td>
                      <td className="py-3 px-4">{customer.email || '-'}</td>
                      <td className="py-3 px-4">
                        {(customer as any)._count?.contracts || 0}
                      </td>
                      <td className="py-3 px-4 text-right">
                        <div className="flex justify-end gap-2">
                          <Link to={`/customers/${customer.id}`}>
                            <Button variant="ghost" size="sm">
                              <Eye className="w-4 h-4" />
                            </Button>
                          </Link>
                          {hasPermission('customers:update') && (
                            <Link to={`/customers/${customer.id}/edit`}>
                              <Button variant="ghost" size="sm">
                                <Edit className="w-4 h-4" />
                              </Button>
                            </Link>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {data.pagination && data.pagination.totalPages > 1 && (
              <div className="mt-4 flex items-center justify-between">
                <p className="text-sm text-gray-500">
                  Seite {data.pagination.page} von {data.pagination.totalPages} ({data.pagination.total} Einträge)
                </p>
                <div className="flex gap-2">
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page === 1}
                  >
                    Zurück
                  </Button>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => setPage((p) => p + 1)}
                    disabled={page >= data.pagination.totalPages}
                  >
                    Weiter
                  </Button>
                </div>
              </div>
            )}
          </>
        ) : (
          <div className="text-center py-8 text-gray-500">
            Keine Kunden gefunden.
          </div>
        )}
      </Card>
    </div>
  );
}
