import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { UserCheck, Send } from "lucide-react";

interface User {
  id: string;
  username: string;
  fullName: string;
  department: string;
}

interface FormAssignmentProps {
  formId: string;
  currentDepartment: string;
  nextDepartment?: string;
  onAssigned?: () => void;
}

export default function FormAssignment({ 
  formId, 
  currentDepartment, 
  nextDepartment,
  onAssigned 
}: FormAssignmentProps) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedUserId, setSelectedUserId] = useState("");
  const [notes, setNotes] = useState("");

  // Get users from target department
  const targetDepartment = nextDepartment || getNextDepartment(currentDepartment);
  
  const { data: users = [] } = useQuery<User[]>({
    queryKey: ["/api/users/by-department", targetDepartment],
    enabled: !!targetDepartment,
  });

  const assignFormMutation = useMutation({
    mutationFn: async (assignmentData: {
      formId: string;
      assignedToUserId: string;
      toDepartment: string;
      notes?: string;
    }) => {
      const response = await apiRequest("POST", "/api/forms/assign", assignmentData);
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "فرم با موفقیت ارجاع داده شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/monitoring"] });
      onAssigned?.();
    },
    onError: (error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در ارجاع فرم",
        variant: "destructive",
      });
    },
  });

  const handleAssign = () => {
    if (!selectedUserId) {
      toast({
        title: "خطا",
        description: "لطفاً فرد مسئول را انتخاب کنید",
        variant: "destructive",
      });
      return;
    }

    assignFormMutation.mutate({
      formId,
      assignedToUserId: selectedUserId,
      toDepartment: targetDepartment,
      notes,
    });
  };

  function getNextDepartment(current: string): string {
    const flow = ['engineering', 'planning', 'commercial', 'quality', 'financial', 'laboratory', 'warehouse'];
    const currentIndex = flow.indexOf(current);
    return currentIndex >= 0 && currentIndex < flow.length - 1 ? flow[currentIndex + 1] : '';
  }

  function getDepartmentName(dept: string): string {
    const names: Record<string, string> = {
      engineering: 'مهندسی',
      planning: 'برنامه‌ریزی', 
      commercial: 'بازرگانی',
      quality: 'تضمین کیفیت',
      financial: 'مالی',
      laboratory: 'آزمایشگاه',
      warehouse: 'انبار',
    };
    return names[dept] || dept;
  }

  if (!targetDepartment) {
    return (
      <Card>
        <CardContent className="pt-6">
          <p className="text-center text-gray-500">
            این فرم در آخرین مرحله قرار دارد
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <UserCheck className="h-5 w-5" />
          ارجاع به واحد {getDepartmentName(targetDepartment)}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div>
          <Label htmlFor="assignedUser">انتخاب فرد مسئول</Label>
          <Select value={selectedUserId} onValueChange={setSelectedUserId}>
            <SelectTrigger>
              <SelectValue placeholder="انتخاب کاربر..." />
            </SelectTrigger>
            <SelectContent>
              {users.map((user) => (
                <SelectItem key={user.id} value={user.id}>
                  {user.fullName} ({user.username})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label htmlFor="notes">یادداشت (اختیاری)</Label>
          <Textarea
            id="notes"
            placeholder="یادداشت برای فرد مسئول..."
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={3}
          />
        </div>

        <Button 
          onClick={handleAssign}
          disabled={assignFormMutation.isPending || !selectedUserId}
          className="w-full flex items-center gap-2"
        >
          <Send className="h-4 w-4" />
          ارجاع فرم
        </Button>
      </CardContent>
    </Card>
  );
}