import { useState, useEffect, useCallback } from 'react';
import { databases, DATABASE_ID } from '@/lib/appwrite';
import { Query } from 'appwrite';
import { useLagerstandorte } from '@/hooks/useLagerstandorte';
import LagerstandortManager from './LagerstandortManager';
import UserAssignDialog from './UserAssignDialog';
import UserCreateForm from './UserCreateForm';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { AlertCircle } from 'lucide-react';

const ROLE_LABELS = {
  admin: 'Admin',
  firmenleiter: 'Firmenleiter',
  filialleiter: 'Filialleiter',
  service: 'Service',
  lager: 'Lager',
};

export default function FilialDetail({ location: loc, onClose, showToast, onUserAdded }) {
  const [users, setUsers] = useState([]);
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [showUserForm, setShowUserForm] = useState(false);
  const [showLsManager, setShowLsManager] = useState(false);

  const { lagerstandorte, addLagerstandort, toggleLagerstandort, deleteLagerstandort } = useLagerstandorte(loc?.$id || '');

  const loadUsers = useCallback(async () => {
    if (!loc?.$id) return;
    try {
      const res = await databases.listDocuments(DATABASE_ID, 'users_meta', [
        Query.equal('locationId', [loc.$id]),
        Query.limit(200),
      ]);
      setUsers(res.documents);
    } catch (err) {
      console.error('Benutzer laden fehlgeschlagen:', err);
    }
  }, [loc?.$id]);

  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  const hasFilialleiter = users.some((u) => u.role === 'filialleiter');

  return (
    <div className="rounded-lg border border-t-0 bg-muted/30 p-4">
      <div className="mb-4 flex items-center justify-between">
        <h3 className="font-semibold">Details: {loc?.name}</h3>
        <Button variant="ghost" size="sm" onClick={onClose}>
          Schließen
        </Button>
      </div>

      {!hasFilialleiter && (
        <div className="mb-4 flex items-center gap-2 rounded-md border border-amber-500/50 bg-amber-500/10 px-3 py-2 text-sm">
          <AlertCircle className="h-4 w-4 shrink-0 text-amber-600" />
          <Badge variant="outline" className="border-amber-600 text-amber-700">
            Filialleiter fehlt
          </Badge>
        </div>
      )}

      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base">Lagerstandorte</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button size="sm" variant="outline" className="w-full" onClick={() => setShowLsManager(true)}>
              Lagerstandorte verwalten
            </Button>
            <div className="max-h-48 space-y-2 overflow-y-auto">
              {lagerstandorte.length === 0 ? (
                <p className="text-center text-sm text-muted-foreground">Keine Lagerstandorte</p>
              ) : (
                lagerstandorte.map((ls) => (
                  <div key={ls.$id} className="flex items-center justify-between rounded border px-2 py-1.5 text-sm">
                    <span className={ls.isActive ? '' : 'text-muted-foreground line-through'}>{ls.name}</span>
                    <Badge variant={ls.isActive ? 'default' : 'secondary'}>{ls.isActive ? 'Aktiv' : 'Inaktiv'}</Badge>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base">Benutzer dieser Filiale</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex gap-2">
              <Button size="sm" variant="outline" className="flex-1" onClick={() => setShowAssignDialog(true)}>
                Benutzer zuordnen
              </Button>
              <Button size="sm" variant="outline" className="flex-1" onClick={() => setShowUserForm(true)}>
                Neuer Benutzer
              </Button>
            </div>
            <div className="max-h-48 space-y-2 overflow-y-auto">
              {users.length === 0 ? (
                <p className="text-center text-sm text-muted-foreground">Keine Benutzer</p>
              ) : (
                users.map((u) => (
                  <div key={u.$id} className="flex items-center justify-between rounded border px-2 py-1.5 text-sm">
                    <span className="font-medium">{u.userName || u.userId}</span>
                    <Badge variant="secondary">{ROLE_LABELS[u.role] || u.role}</Badge>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {showLsManager && (
        <LagerstandortManager
          lagerstandorte={lagerstandorte}
          onAdd={addLagerstandort}
          onToggle={toggleLagerstandort}
          onDelete={deleteLagerstandort}
          onClose={() => setShowLsManager(false)}
        />
      )}

      {showAssignDialog && (
        <UserAssignDialog
          location={loc}
          onClose={() => setShowAssignDialog(false)}
          onSuccess={() => {
            loadUsers();
            setShowAssignDialog(false);
            onUserAdded?.();
          }}
          showToast={showToast}
        />
      )}

      {showUserForm && (
        <UserCreateForm
          locationId={loc?.$id}
          locationName={loc?.name}
          onSuccess={() => {
            loadUsers();
            setShowUserForm(false);
            onUserAdded?.();
          }}
          onCancel={() => setShowUserForm(false)}
          showToast={showToast}
        />
      )}
    </div>
  );
}
