import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { toast as sonnerToast } from "sonner";
import { Loader2 } from "lucide-react";

interface BulkTaskDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedUnits: {
    unitKey: string;
    unitId: string | null;
    unitNumber: string;
    ownerNames: string[];
    associationId: string;
    associationName: string;
    balance: number;
  }[];
  users: { id: string; name: string }[];
  onSuccess: () => void;
}

export default function BulkTaskDialog({ open, onOpenChange, selectedUnits, users, onSuccess }: BulkTaskDialogProps) {
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    title: "",
    description: "",
    priority: "medium",
    assigned_to: "unassigned",
    due_date: "",
  });

  const handleSubmit = async () => {
    if (!form.title.trim()) {
      sonnerToast.error("Task title is required");
      return;
    }

    setLoading(true);
    try {
      const tasks = selectedUnits.map((unit) => ({
        title: form.title.replace("{unit}", unit.unitNumber).replace("{owner}", unit.ownerNames.join(", ")).replace("{association}", unit.associationName).replace("{balance}", `$${unit.balance.toFixed(2)}`),
        description: form.description.replace("{unit}", unit.unitNumber).replace("{owner}", unit.ownerNames.join(", ")).replace("{association}", unit.associationName).replace("{balance}", `$${unit.balance.toFixed(2)}`),
        priority: form.priority,
        assigned_to: form.assigned_to === "unassigned" ? null : form.assigned_to,
        due_date: form.due_date || null,
        status: "pending",
        association_id: unit.associationId,
        created_by: user?.id || null,
      }));

      const { error } = await supabase.from("tasks").insert(tasks);
      if (error) throw error;

      sonnerToast.success(`${tasks.length} task(s) created successfully`);
      onOpenChange(false);
      setForm({ title: "", description: "", priority: "medium", assigned_to: "unassigned", due_date: "" });
      onSuccess();
    } catch (err: any) {
      sonnerToast.error("Failed to create tasks", { description: err.message });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Create Bulk Tasks</DialogTitle>
          <DialogDescription>
            Create a task for each of the {selectedUnits.length} selected unit(s).
            Use placeholders: {"{unit}"}, {"{owner}"}, {"{association}"}, {"{balance}"}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-2">
            <Label>Task Title *</Label>
            <Input
              placeholder="e.g. Follow up on balance for unit {unit}"
              value={form.title}
              onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
            />
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea
              placeholder="e.g. Contact {owner} regarding outstanding balance of {balance}"
              value={form.description}
              onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
              rows={3}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Priority</Label>
              <Select value={form.priority} onValueChange={(v) => setForm((f) => ({ ...f, priority: v }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">Low</SelectItem>
                  <SelectItem value="medium">Medium</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                  <SelectItem value="urgent">Urgent</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Assign To</Label>
              <Select value={form.assigned_to} onValueChange={(v) => setForm((f) => ({ ...f, assigned_to: v }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="unassigned">Unassigned</SelectItem>
                  {users.map((u) => (
                    <SelectItem key={u.id} value={u.id}>{u.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-2">
            <Label>Due Date</Label>
            <Input
              type="date"
              value={form.due_date}
              onChange={(e) => setForm((f) => ({ ...f, due_date: e.target.value }))}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={loading} className="gap-2">
            {loading && <Loader2 className="h-4 w-4 animate-spin" />}
            Create {selectedUnits.length} Task(s)
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
