import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Trash2, Loader2, ChevronRight, Settings2, ArrowRight } from "lucide-react";
import { approvalsService, type ApprovalWorkflow } from "@/services/approvals.service";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";

interface WorkflowStage {
  order: number;
  approver_id: number;
  approver_name: string;
  max_days?: number;
  notification_email?: string;
  auto_escalate?: boolean;
}

export default function ApprovalWorkflowConfig() {
  const { toast } = useToast();
  const qc = useQueryClient();

  const { data: workflowsData, isLoading } = useQuery({
    queryKey: ["approvals", "list"],
    queryFn: () => approvalsService.list(),
  });
  const workflows = workflowsData?.results ?? [];

  const createWorkflow = useMutation({
    mutationFn: (data: Partial<ApprovalWorkflow>) => approvalsService.create(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["approvals"] }),
    onError: () => toast({ title: "Error", description: "Failed to create workflow", variant: "destructive" }),
  });

  const updateWorkflow = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<ApprovalWorkflow> }) => approvalsService.update(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["approvals"] }),
    onError: () => toast({ title: "Error", description: "Failed to update workflow", variant: "destructive" }),
  });

  const deleteWorkflow = useMutation({
    mutationFn: (id: number) => approvalsService.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["approvals"] }),
    onError: () => toast({ title: "Error", description: "Failed to delete workflow", variant: "destructive" }),
  });

  const [showCreate, setShowCreate] = useState(false);
  const [wfName, setWfName] = useState("");
  const [stages, setStages] = useState<WorkflowStage[]>([{ order: 1, approver_id: 0, approver_name: "", max_days: 3, auto_escalate: false }]);
  const [bypassEnabled, setBypassEnabled] = useState(false);

  const resetForm = () => {
    setWfName("");
    setStages([{ order: 1, approver_id: 0, approver_name: "", max_days: 3, auto_escalate: false }]);
    setBypassEnabled(false);
  };

  const addStage = () => {
    setStages(prev => [...prev, { order: prev.length + 1, approver_id: 0, approver_name: "", max_days: 3, auto_escalate: false }]);
  };

  const removeStage = (idx: number) => {
    setStages(prev => prev.filter((_, i) => i !== idx).map((s, i) => ({ ...s, order: i + 1 })));
  };

  const updateStage = (idx: number, field: keyof WorkflowStage, value: string | number | boolean) => {
    setStages(prev => prev.map((s, i) => i === idx ? { ...s, [field]: value } : s));
  };

  const handleCreate = () => {
    createWorkflow.mutate(
      { name: wfName, steps: stages.map(s => ({ order: s.order, approver_id: s.approver_id, approver_name: s.approver_name })), status: "draft" } as Partial<ApprovalWorkflow>,
      { onSuccess: () => { toast({ title: "Workflow Created" }); setShowCreate(false); resetForm(); } },
    );
  };

  const handleDelete = (id: number) => {
    if (!window.confirm("Delete this approval workflow?")) return;
    deleteWorkflow.mutate(id, {
      onSuccess: () => toast({ title: "Workflow Deleted" }),
    });
  };

  const handleToggleStatus = (wf: ApprovalWorkflow) => {
    const newStatus = wf.status === "active" ? "draft" : "active";
    updateWorkflow.mutate(
      { id: wf.id, data: { status: newStatus } },
      { onSuccess: () => toast({ title: `Workflow ${newStatus === "active" ? "Activated" : "Deactivated"}` }) },
    );
  };

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Approval Workflows</h1>
          <p className="text-muted-foreground">Configure multi-stage approval workflows with escalation rules.</p>
        </div>
        <Dialog open={showCreate} onOpenChange={open => { setShowCreate(open); if (!open) resetForm(); }}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Workflow</Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader><DialogTitle>Create Approval Workflow</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Workflow Name</Label>
                <Input placeholder="e.g. Leave Approval" value={wfName} onChange={e => setWfName(e.target.value)} />
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label>Stages</Label>
                  <Button variant="outline" size="sm" onClick={addStage}><Plus className="mr-2 h-3 w-3" /> Add Stage</Button>
                </div>
                {stages.map((stage, idx) => (
                  <Card key={idx}>
                    <CardContent className="py-3 space-y-3">
                      <div className="flex items-center justify-between">
                        <Badge variant="outline">Stage {stage.order}</Badge>
                        {stages.length > 1 && (
                          <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => removeStage(idx)}>
                            <Trash2 className="h-3 w-3 text-destructive" />
                          </Button>
                        )}
                      </div>
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                          <Label className="text-xs">Approver Name</Label>
                          <Input value={stage.approver_name} onChange={e => updateStage(idx, "approver_name", e.target.value)} placeholder="Name" />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Approver ID</Label>
                          <Input type="number" value={stage.approver_id || ""} onChange={e => updateStage(idx, "approver_id", Number(e.target.value))} placeholder="ID" />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Max Days</Label>
                          <Input type="number" min={1} value={stage.max_days ?? 3} onChange={e => updateStage(idx, "max_days", Number(e.target.value))} />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Email</Label>
                          <Input type="email" value={stage.notification_email ?? ""} onChange={e => updateStage(idx, "notification_email", e.target.value)} placeholder="email@..." />
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Switch checked={!!stage.auto_escalate} onCheckedChange={v => updateStage(idx, "auto_escalate", v)} />
                        <Label className="text-xs">Auto-escalate after max days</Label>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>

              <div className="flex items-center gap-2 p-3 rounded-lg border">
                <Switch checked={bypassEnabled} onCheckedChange={setBypassEnabled} />
                <Label>Allow bypass (skip all stages)</Label>
              </div>

              <Button className="w-full" onClick={handleCreate} disabled={createWorkflow.isPending || !wfName || stages.length === 0}>
                {createWorkflow.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Workflow
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="space-y-4">
        {workflows.map(wf => (
          <Card key={wf.id}>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Settings2 className="h-5 w-5 text-primary" />
                  <div>
                    <CardTitle className="text-base">{wf.name}</CardTitle>
                    <CardDescription>{wf.entity_name}</CardDescription>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={wf.status === "active" ? "default" : "secondary"}>{wf.status}</Badge>
                  <Switch checked={wf.status === "active"} onCheckedChange={() => handleToggleStatus(wf)} />
                  <Button variant="ghost" size="icon" onClick={() => handleDelete(wf.id)} disabled={deleteWorkflow.isPending}>
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-2 flex-wrap">
                {wf.steps.map((step, i) => (
                  <div key={i} className="flex items-center gap-2">
                    <div className="flex items-center gap-1 px-3 py-1.5 rounded-full border bg-muted/50 text-sm">
                      <span className="h-5 w-5 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-medium">{step.order}</span>
                      <span>{step.approver_name}</span>
                    </div>
                    {i < wf.steps.length - 1 && <ArrowRight className="h-4 w-4 text-muted-foreground" />}
                  </div>
                ))}
              </div>
              <p className="text-xs text-muted-foreground mt-2">Created: {new Date(wf.created_at).toLocaleDateString()}</p>
            </CardContent>
          </Card>
        ))}
        {workflows.length === 0 && (
          <Card>
            <CardContent className="py-12 text-center text-muted-foreground">
              <Settings2 className="h-12 w-12 mx-auto mb-3 opacity-40" />
              <p>No approval workflows configured.</p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
