/**
 * 流程属性面板 - 编辑节点属性
 */

'use client';

import React from 'react';
import {
  Settings,
  User,
  Users,
  Clock,
  Shield,
  ChevronDown,
  X,
} from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { useProcessDesignerStore, useSelectedNode } from './useProcessDesignerStore';
import {
  APPROVER_TYPES,
  APPROVAL_MODES,
  ApproverType,
  ApprovalMode,
  ProcessNode,
} from './types';
import { useTranslation } from '@/hooks/useTranslation';

function EmptyState() {
  return (
    <div className="h-full flex items-center justify-center">
      <div className="text-center text-gray-400 px-8">
        <Settings className="w-12 h-12 mx-auto mb-3 opacity-50" />
        <p className="text-sm">选择节点查看属性</p>
        <p className="text-xs mt-1">点击画布中的节点进行配置</p>
      </div>
    </div>
  );
}

function StartEndNodeProperties({ node, t }: { node: ProcessNode; t: any }) {
  const { updateNode } = useProcessDesignerStore();

  return (
    <div className="space-y-4 p-4">
      {/* 基本信息 */}
      <div className="space-y-2">
        <Label htmlFor="node-name">节点名称</Label>
        <Input
          id="node-name"
          value={node.name}
          onChange={(e) => updateNode(node.id, { name: e.target.value })}
        />
      </div>

      <div className="pt-4 text-center text-sm text-gray-500">
        <p>{node.type === 'START' ? t.approvals.propertyPanel.startNodeDesc : t.approvals.propertyPanel.endNodeDesc}</p>
        <p className="text-xs mt-1">{t.approvals.propertyPanel.noOtherConfig}</p>
      </div>
    </div>
  );
}

function UserTaskProperties({ node, t }: { node: ProcessNode; t: any }) {
  const { updateNode, updateNodeConfig } = useProcessDesignerStore();
  const config = node.config;

  return (
    <Tabs defaultValue="approver" className="flex-1 flex flex-col">
      <TabsList className="mx-4 mt-4">
        <TabsTrigger value="approver" className="flex-1">
          <User className="w-4 h-4 mr-1" />
          审批人
        </TabsTrigger>
        <TabsTrigger value="advanced" className="flex-1">
          <Settings className="w-4 h-4 mr-1" />
          高级
        </TabsTrigger>
      </TabsList>

      <TabsContent value="approver" className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* 节点名称 */}
        <div className="space-y-2">
          <Label htmlFor="node-name">节点名称</Label>
          <Input
            id="node-name"
            value={node.name}
            onChange={(e) => updateNode(node.id, { name: e.target.value })}
            placeholder="如：主管审批"
          />
        </div>

        {/* 审批人类型 */}
        <div className="space-y-2">
          <Label>审批人类型</Label>
          <Select
            value={config.approverType || 'INITIATOR_MANAGER'}
            onValueChange={(value: ApproverType) =>
              updateNodeConfig(node.id, { approverType: value })
            }
          >
          <SelectTrigger>
            <SelectValue placeholder={t.approvals.propertyPanel.selectApproverType} />
            </SelectTrigger>
            <SelectContent>
              {APPROVER_TYPES.map((type) => (
                <SelectItem key={type.value} value={type.value}>
                  <div>
                    <div className="font-medium">{type.label}</div>
                    <div className="text-xs text-gray-500">{type.description}</div>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 连续上级配置 */}
        {config.approverType === 'MANAGER_CHAIN' && (
          <div className="space-y-3 p-3 bg-gray-50 rounded-lg">
            <div className="text-sm font-medium text-gray-700">连续上级配置</div>
            
            <div className="space-y-2">
              <Label>终止条件</Label>
              <Select
                value={config.chainConfig?.stopCondition || 'deptHead'}
                onValueChange={(value) =>
                  updateNodeConfig(node.id, {
                    chainConfig: {
                      ...config.chainConfig,
                      stopCondition: value,
                    },
                  })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="deptHead">部门负责人</SelectItem>
                  <SelectItem value="orgHead">组织负责人</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>最大审批层级</Label>
              <Input
                type="number"
                min={1}
                max={20}
                value={config.chainConfig?.maxLevels || 10}
                onChange={(e) =>
                  updateNodeConfig(node.id, {
                    chainConfig: {
                      ...config.chainConfig,
                      maxLevels: parseInt(e.target.value) || 10,
                    },
                  })
                }
              />
            </div>

            <div className="flex items-center justify-between">
              <Label htmlFor="skip-self">跳过发起人</Label>
              <Switch
                id="skip-self"
                checked={config.chainConfig?.skipSelf !== false}
                onCheckedChange={(checked) =>
                  updateNodeConfig(node.id, {
                    chainConfig: {
                      ...config.chainConfig,
                      skipSelf: checked,
                    },
                  })
                }
              />
            </div>

            <div className="space-y-2">
              <Label>自动通过规则</Label>
              <Select
                value={config.chainConfig?.autoApprove || 'both'}
                onValueChange={(value: any) =>
                  updateNodeConfig(node.id, {
                    chainConfig: {
                      ...config.chainConfig,
                      autoApprove: value,
                    },
                  })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">不自动通过</SelectItem>
                  <SelectItem value="sameApprover">同一审批人</SelectItem>
                  <SelectItem value="initiator">发起人是审批人</SelectItem>
                  <SelectItem value="both">两种情况都自动通过</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        )}

        {/* 审批模式 */}
        {config.approverType !== 'MANAGER_CHAIN' && (
          <div className="space-y-2">
            <Label>审批模式</Label>
            <Select
              value={config.approvalMode || 'SINGLE'}
              onValueChange={(value: ApprovalMode) =>
                updateNodeConfig(node.id, { approvalMode: value })
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {APPROVAL_MODES.map((mode) => (
                  <SelectItem key={mode.value} value={mode.value}>
                    <div>
                      <div className="font-medium">{mode.label}</div>
                      <div className="text-xs text-gray-500">{mode.description}</div>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}
      </TabsContent>

      <TabsContent value="advanced" className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* 超时配置 */}
        <Collapsible defaultOpen>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-2 bg-gray-50 rounded-lg hover:bg-gray-100">
            <div className="flex items-center gap-2">
              <Clock className="w-4 h-4 text-gray-500" />
              <span className="text-sm font-medium">超时设置</span>
            </div>
            <ChevronDown className="w-4 h-4 text-gray-400" />
          </CollapsibleTrigger>
          <CollapsibleContent className="pt-3 space-y-3">
            <div className="space-y-2">
              <Label>超时时间（小时）</Label>
              <Input
                type="number"
                min={0}
                value={config.timeout?.hours || 0}
                onChange={(e) => {
                  const hours = parseInt(e.target.value) || 0;
                  updateNodeConfig(node.id, {
                    timeout: {
                      hours,
                      remindBeforeHours: config.timeout?.remindBeforeHours,
                      action: config.timeout?.action,
                    },
                  });
                }}
                placeholder="0 表示不限时"
              />
            </div>

            {(config.timeout?.hours || 0) > 0 && (
              <>
                <div className="space-y-2">
                  <Label>超时前提醒（小时）</Label>
                  <Input
                    type="number"
                    min={0}
                    max={config.timeout?.hours || 24}
                    value={config.timeout?.remindBeforeHours || 0}
                    onChange={(e) =>
                      updateNodeConfig(node.id, {
                        timeout: {
                          hours: config.timeout?.hours || 24,
                          ...config.timeout,
                          remindBeforeHours: parseInt(e.target.value) || 0,
                        },
                      })
                    }
                  />
                </div>

                <div className="space-y-2">
                  <Label>超时处理</Label>
                  <Select
                    value={config.timeout?.action || 'remind'}
                    onValueChange={(value: any) =>
                      updateNodeConfig(node.id, {
                        timeout: {
                          hours: config.timeout?.hours || 24,
                          ...config.timeout,
                          action: value,
                        },
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="remind">仅催办</SelectItem>
                      <SelectItem value="escalate">升级到上级</SelectItem>
                      <SelectItem value="auto_approve">自动通过</SelectItem>
                      <SelectItem value="auto_reject">自动驳回</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </>
            )}
          </CollapsibleContent>
        </Collapsible>

        {/* 操作权限 */}
        <Collapsible>
          <CollapsibleTrigger className="flex items-center justify-between w-full p-2 bg-gray-50 rounded-lg hover:bg-gray-100">
            <div className="flex items-center gap-2">
              <Shield className="w-4 h-4 text-gray-500" />
              <span className="text-sm font-medium">操作权限</span>
            </div>
            <ChevronDown className="w-4 h-4 text-gray-400" />
          </CollapsibleTrigger>
          <CollapsibleContent className="pt-3 space-y-2">
            {[
              { key: 'APPROVE', label: t.approvals.propertyPanel.actions.approve },
              { key: 'REJECT', label: t.approvals.propertyPanel.actions.reject },
              { key: 'RETURN', label: t.approvals.propertyPanel.actions.return },
              { key: 'FORWARD', label: t.approvals.propertyPanel.actions.forward },
              { key: 'ADD_SIGN', label: t.approvals.propertyPanel.actions.addSign },
            ].map((action) => (
              <div key={action.key} className="flex items-center justify-between">
                <Label htmlFor={`action-${action.key}`}>{action.label}</Label>
                <Switch
                  id={`action-${action.key}`}
                  checked={
                    !config.allowedActions ||
                    config.allowedActions.includes(action.key)
                  }
                  onCheckedChange={(checked) => {
                    const current = config.allowedActions || [
                      'APPROVE',
                      'REJECT',
                      'RETURN',
                      'FORWARD',
                      'ADD_SIGN',
                    ];
                    const updated = checked
                      ? [...current, action.key]
                      : current.filter((a) => a !== action.key);
                    updateNodeConfig(node.id, { allowedActions: updated });
                  }}
                />
              </div>
            ))}
          </CollapsibleContent>
        </Collapsible>
      </TabsContent>
    </Tabs>
  );
}

function GatewayProperties({ node, t, isParallel = false }: { node: ProcessNode; t: any; isParallel?: boolean }) {
  const { updateNode, updateNodeConfig, edges } = useProcessDesignerStore();

  // 获取从该节点出发的边
  const outgoingEdges = edges.filter((e) => e.source === node.id);

  return (
    <div className="p-4 space-y-4">
      {/* 节点名称 */}
      <div className="space-y-2">
        <Label htmlFor="node-name">节点名称</Label>
        <Input
          id="node-name"
          value={node.name}
          onChange={(e) => updateNode(node.id, { name: e.target.value })}
        />
      </div>

      {/* 网关类型说明 */}
      <div className="p-3 bg-gray-50 rounded-lg">
        <div className="text-sm font-medium text-gray-700 mb-1">
          {isParallel ? t.approvals.propertyPanel.parallelGateway : t.approvals.propertyPanel.conditionalGateway}
        </div>
        <p className="text-xs text-gray-500">
          {isParallel
            ? t.approvals.propertyPanel.parallelGatewayDesc
            : t.approvals.propertyPanel.conditionalGatewayDesc}
        </p>
      </div>

      {/* 条件配置（排他网关） */}
      {!isParallel && outgoingEdges.length > 0 && (
        <div className="space-y-3">
          <Label>分支条件</Label>
          <div className="space-y-2">
            {outgoingEdges.map((edge, index) => (
              <div key={edge.id} className="p-2 border rounded-lg space-y-2">
                <div className="text-xs text-gray-500">分支 {index + 1}</div>
                <Input
                  value={edge.label || ''}
                  onChange={(e) => {
                    const { edges, updateEdge } = useProcessDesignerStore.getState();
                    updateEdge(edge.id, { label: e.target.value });
                  }}
                  placeholder={t.approvals.propertyPanel.conditionName}
                />
                <Input
                  value={edge.condition || ''}
                  onChange={(e) => {
                    const { updateEdge } = useProcessDesignerStore.getState();
                    updateEdge(edge.id, { condition: e.target.value });
                  }}
                  placeholder="条件表达式，如: amount > 10000"
                  className="font-mono text-xs"
                />
              </div>
            ))}
          </div>
          <p className="text-xs text-gray-500">
            提示：条件表达式支持引用表单字段，如 {'{amount}'} {'>'} 10000
          </p>
        </div>
      )}
    </div>
  );
}

function CCNodeProperties({ node, t }: { node: ProcessNode; t: any }) {
  const { updateNode, updateNodeConfig } = useProcessDesignerStore();
  const config = node.config;

  return (
    <div className="p-4 space-y-4">
      {/* 节点名称 */}
      <div className="space-y-2">
        <Label htmlFor="node-name">节点名称</Label>
        <Input
          id="node-name"
          value={node.name}
          onChange={(e) => updateNode(node.id, { name: e.target.value })}
        />
      </div>

      {/* 抄送说明 */}
      <div className="p-3 bg-purple-50 rounded-lg">
        <div className="text-sm font-medium text-purple-700 mb-1">抄送节点</div>
        <p className="text-xs text-purple-600">
          将流程信息通知给指定人员，不阻断流程执行
        </p>
      </div>

      {/* 抄送对象配置 */}
      <div className="space-y-2">
        <Label>抄送对象</Label>
        <Select
          value={config.approverType || 'FIXED_USER'}
          onValueChange={(value: ApproverType) =>
            updateNodeConfig(node.id, { approverType: value })
          }
        >
          <SelectTrigger>
            <SelectValue placeholder={t.approvals.propertyPanel.selectCCType} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="FIXED_USER">{t.approvals.approverTypesConfig.fixedUser.label}</SelectItem>
            <SelectItem value="ROLE">{t.approvals.approverTypesConfig.role.label}</SelectItem>
            <SelectItem value="INITIATOR_MANAGER">{t.approvals.approverTypesConfig.initiatorManager.label}</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  );
}

export function ProcessPropertyPanel() {
  const { t } = useTranslation();
  const selectedNode = useSelectedNode();
  const { selectNode } = useProcessDesignerStore();

  if (!selectedNode) {
    return (
      <div className="w-72 bg-white border-l border-gray-200 flex flex-col">
        <div className="px-4 py-3 border-b border-gray-200">
          <h3 className="text-sm font-semibold text-gray-700">属性配置</h3>
        </div>
        <EmptyState />
      </div>
    );
  }

  return (
    <div className="w-72 bg-white border-l border-gray-200 flex flex-col h-full">
      {/* 标题 */}
      <div className="px-4 py-3 border-b border-gray-200 flex items-center justify-between">
        <h3 className="text-sm font-semibold text-gray-700">属性配置</h3>
        <button
          onClick={() => selectNode(null)}
          className="p-1 hover:bg-gray-100 rounded"
        >
          <X className="w-4 h-4 text-gray-400" />
        </button>
      </div>

      {/* 属性内容 */}
      <div className="flex-1 overflow-hidden flex flex-col">
        {(selectedNode.type === 'START' || selectedNode.type === 'END') && (
          <StartEndNodeProperties node={selectedNode} t={t} />
        )}

        {selectedNode.type === 'USER_TASK' && (
          <UserTaskProperties node={selectedNode} t={t} />
        )}

        {(selectedNode.type === 'EXCLUSIVE_GATEWAY' ||
          selectedNode.type === 'PARALLEL_GATEWAY') && (
          <GatewayProperties node={selectedNode} t={t} />
        )}

        {selectedNode.type === 'CC' && (
          <CCNodeProperties node={selectedNode} t={t} />
        )}
      </div>
    </div>
  );
}
