import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Send, Building2 } from "lucide-react";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useLocation } from "wouter";

interface User {
  id: string;
  username: string;
  fullName: string;
  department: string;
  position?: string;
  isActive: boolean;
}

interface FormDelegationProps {
  formId: string;
  currentDepartment: string;
  onSuccess?: () => void;
  onBeforeDelegate?: () => Promise<void>;
}

const departmentNames: Record<string, string> = {
  engineering: 'مهندسی',
  planning: 'برنامه‌ریزی',
  commercial: 'بازرگانی',
  quality: 'تضمین کیفیت',
  financial: 'مالی',
  laboratory: 'تست آزمایشگاهی',
  warehouse: 'انبار',
  admin: 'مدیریت'
};

const allDepartments = [
  { value: 'engineering', label: 'مهندسی' },
  { value: 'planning', label: 'برنامه‌ریزی' },
  { value: 'commercial', label: 'بازرگانی' },
  { value: 'quality', label: 'تضمین کیفیت' },
  { value: 'financial', label: 'مالی' },
  { value: 'laboratory', label: 'تست آزمایشگاهی' },
  { value: 'warehouse', label: 'انبار' },
  { value: 'admin', label: 'مدیریت' }
];

export default function FormDelegation({ formId, currentDepartment, onSuccess, onBeforeDelegate }: FormDelegationProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedDepartment, setSelectedDepartment] = useState<string>("");
  const [selectedUserId, setSelectedUserId] = useState<string>("");
  const [notes, setNotes] = useState("");
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [, navigate] = useLocation();

  // Get available departments (include current for internal delegation)
  const availableDepartments = allDepartments;

  // Fetch users of selected department
  const { data: departmentUsers = [] } = useQuery({
    queryKey: ["/api/users/by-department", selectedDepartment],
    queryFn: async () => {
      const response = await fetch(`/api/users/by-department/${selectedDepartment}`);
      if (!response.ok) throw new Error('Failed to fetch users');
      return response.json();
    },
    enabled: !!selectedDepartment && isOpen,
  });

  // Filter active users
  const availableUsers = departmentUsers.filter((user: User) => user.isActive !== false);

  const delegateFormMutation = useMutation({
    mutationFn: async () => {
      if (!selectedDepartment) {
        throw new Error("لطفاً واحد مقصد را انتخاب کنید");
      }

      if (!selectedUserId) {
        throw new Error("لطفاً کاربر مقصد را انتخاب کنید");
      }

      const selectedUser = availableUsers.find((u: User) => u.id === selectedUserId);
      if (!selectedUser) {
        throw new Error("کاربر انتخاب شده یافت نشد");
      }

      // Save form data before delegation
      if (onBeforeDelegate) {
        await onBeforeDelegate();
      }

      const response = await fetch(`/api/forms/${formId}/delegate`, {
        method: "POST",
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          assignedToUserId: selectedUserId,
          toDepartment: selectedDepartment,
          notes: notes || `ارجاع به ${selectedUser.fullName} - ${departmentNames[selectedDepartment]}`
        })
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || 'خطا در ارجاع فرم');
      }

      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "فرم با موفقیت ارجاع داده شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      queryClient.invalidateQueries({ queryKey: [`/api/forms/${formId}`] });
      setIsOpen(false);
      setSelectedDepartment("");
      setSelectedUserId("");
      setNotes("");
      onSuccess?.();
      // Navigate back to home after successful delegation
      setTimeout(() => navigate("/"), 500);
    },
    onError: (error: any) => {
      console.error("Delegation error:", error);
      toast({
        title: "خطا",
        description: error.message || "خطا در ارجاع فرم",
        variant: "destructive",
      });
    },
  });

  const handleDelegate = () => {
    delegateFormMutation.mutate();
  };

  // Reset user selection when department changes
  const handleDepartmentChange = (department: string) => {
    setSelectedDepartment(department);
    setSelectedUserId(""); // Reset user selection
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button
          className="flex items-center gap-2"
          variant="default"
        >
          <Send className="h-4 w-4" />
          ارجاع به واحد
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]" dir="rtl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Building2 className="h-5 w-5" />
            ارجاع فرم به واحد
          </DialogTitle>
          <DialogDescription>
            فرم را به واحد و کاربر مقصد ارجاع دهید. فرم از لیست شما حذف و به لیست کاربر مقصد اضافه خواهد شد.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="department-select">انتخاب واحد مقصد</Label>
            <Select value={selectedDepartment} onValueChange={handleDepartmentChange}>
              <SelectTrigger>
                <SelectValue placeholder="واحد مورد نظر را انتخاب کنید" />
              </SelectTrigger>
              <SelectContent>
                {availableDepartments.map((dept) => (
                  <SelectItem key={dept.value} value={dept.value}>
                    {dept.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {selectedDepartment && (
            <div className="space-y-2">
              <Label htmlFor="user-select">انتخاب کاربر مقصد</Label>
              <Select value={selectedUserId} onValueChange={setSelectedUserId}>
                <SelectTrigger>
                  <SelectValue placeholder="کاربر مورد نظر را انتخاب کنید" />
                </SelectTrigger>
                <SelectContent>
                  {availableUsers.length > 0 ? (
                    availableUsers.map((user: User) => (
                      <SelectItem key={user.id} value={user.id}>
                        <div className="flex flex-col items-start">
                          <span>{user.fullName}</span>
                          <span className="text-xs text-muted-foreground">
                            {user.position ? `${user.position} - ` : ''}{user.username}
                          </span>
                        </div>
                      </SelectItem>
                    ))
                  ) : (
                    <div className="px-2 py-1 text-sm text-muted-foreground">
                      کاربری در این واحد یافت نشد
                    </div>
                  )}
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="notes">یادداشت (اختیاری)</Label>
            <Textarea
              id="notes"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="دلیل ارجاع یا توضیحات اضافی..."
              className="text-right"
              rows={3}
            />
          </div>

          {selectedUserId && selectedDepartment && (
            <Card className="bg-blue-50 border-blue-200">
              <CardContent className="p-3">
                <div className="text-sm space-y-1">
                  <div>
                    <span className="font-medium">واحد مقصد: </span>
                    {departmentNames[selectedDepartment]}
                  </div>
                  <div>
                    <span className="font-medium">کاربر انتخاب شده: </span>
                    {(() => {
                      const user = availableUsers.find((u: User) => u.id === selectedUserId);
                      return user ? user.fullName : '';
                    })()}
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => setIsOpen(false)}
          >
            انصراف
          </Button>
          <Button
            type="button"
            onClick={handleDelegate}
            disabled={!selectedDepartment || !selectedUserId || delegateFormMutation.isPending}
          >
            {delegateFormMutation.isPending ? "در حال ارجاع..." : "ارجاع فرم"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}