import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Clock, Eye } from "lucide-react";

interface WorkflowHistoryEntry {
  id: string;
  fromDepartment: string;
  toDepartment: string;
  action: string;
  userId: string;
  userName: string;
  notes: string;
  isReturned: boolean;
  signatureApplied: boolean;
  createdAt: string;
}

interface WorkflowHistoryProps {
  formId: string;
}

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

const actionNames: Record<string, string> = {
  created: 'ایجاد شده',
  forwarded: 'ارسال شده',
  completed: 'تکمیل شده',
  rejected: 'رد شده',
  returned: 'برگشت داده شده'
};

export default function WorkflowHistory({ formId }: WorkflowHistoryProps) {
  const { data: history, isLoading } = useQuery({
    queryKey: ['/api/forms', formId, 'history'],
    enabled: !!formId,
  });

  const getActionBadgeVariant = (action: string, isReturned: boolean) => {
    if (isReturned) return "destructive";
    
    switch (action) {
      case 'created': return "default";
      case 'forwarded': return "secondary";
      case 'completed': return "default";
      case 'rejected': return "destructive";
      default: return "default";
    }
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline" className="flex items-center gap-2">
          <Clock className="h-4 w-4" />
          مشاهده چرخه نامه
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-right">تاریخچه گردش فرم</DialogTitle>
        </DialogHeader>
        
        <div className="mt-4">
          {isLoading ? (
            <div className="text-center py-8">در حال بارگذاری...</div>
          ) : !history || (history as any[]).length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              هیچ تاریخچه‌ای برای این فرم ثبت نشده است
            </div>
          ) : (
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">تاریخچه کامل گردش فرم</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-center">تاریخ/زمان</TableHead>
                      <TableHead className="text-center">از واحد</TableHead>
                      <TableHead className="text-center">به واحد</TableHead>
                      <TableHead className="text-center">عملیات</TableHead>
                      <TableHead className="text-center">کاربر</TableHead>
                      <TableHead className="text-center">امضا</TableHead>
                      <TableHead className="text-center">یادداشت</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(history as WorkflowHistoryEntry[]).map((entry: WorkflowHistoryEntry, index: number) => (
                      <TableRow key={entry.id}>
                        <TableCell className="text-center">
                          <div className="text-sm">
                            <div>{new Date(entry.createdAt).toLocaleDateString('fa-IR')}</div>
                            <div className="text-gray-500 text-xs">
                              {new Date(entry.createdAt).toLocaleTimeString('fa-IR')}
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="text-center">
                          {entry.fromDepartment ? departmentNames[entry.fromDepartment] || entry.fromDepartment : '-'}
                        </TableCell>
                        <TableCell className="text-center">
                          {departmentNames[entry.toDepartment] || entry.toDepartment}
                        </TableCell>
                        <TableCell className="text-center">
                          <Badge 
                            variant={getActionBadgeVariant(entry.action, entry.isReturned)}
                            className="text-xs"
                          >
                            {entry.isReturned ? 'برگشت' : actionNames[entry.action] || entry.action}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center text-sm">
                          {entry.userName}
                        </TableCell>
                        <TableCell className="text-center">
                          {entry.signatureApplied ? (
                            <Badge variant="default" className="text-xs">
                              امضا شده
                            </Badge>
                          ) : (
                            <span className="text-gray-400 text-xs">-</span>
                          )}
                        </TableCell>
                        <TableCell className="text-center text-sm">
                          {entry.notes || '-'}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}
        </div>
        
        <div className="mt-4 text-sm text-gray-500 text-center">
          <Eye className="inline h-4 w-4 mr-1" />
          این تاریخچه فقط برای مشاهده است و قابل ویرایش نمی‌باشد
        </div>
      </DialogContent>
    </Dialog>
  );
}