import { useState, useEffect } from "react";
import { format } from "date-fns";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Loader2, X, CheckCheck, CalendarIcon, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";

interface ViolationBulkActionsProps {
  selectedIds: string[];
  onClear: () => void;
  onComplete: () => void;
  /** Association ID scoping the available violation types. If undefined, type selectors are hidden. */
  associationId?: string;
}

const STATUSES = [
  { value: "open", label: "Open" },
  { value: "pending", label: "Notice Sent" },
  { value: "escalated", label: "Second Notice" },
  { value: "recommended_for_fining", label: "Recommended for Fining" },
  { value: "fined", label: "Fining" },
  { value: "resolved", label: "Resolved" },
  { value: "closed", label: "Closed" },
];

const STAGES = [
  { value: "first_notice", label: "1st Notice" },
  { value: "second_notice", label: "2nd Notice" },
  { value: "third_final", label: "Final Notice" },
  { value: "hearing", label: "Hearing" },
  { value: "fining", label: "Fining" },
];

const PRIORITIES = [
  { value: "low", label: "Low" },
  { value: "medium", label: "Medium" },
  { value: "high", label: "High" },
  { value: "critical", label: "Critical" },
];

export default function ViolationBulkActions({ selectedIds, onClear, onComplete, associationId }: ViolationBulkActionsProps) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [bulkStatus, setBulkStatus] = useState("");
  const [bulkStage, setBulkStage] = useState("");
  const [bulkPriority, setBulkPriority] = useState("");
  const [bulkViolationDate, setBulkViolationDate] = useState<Date | undefined>();
  const [bulkDueDate, setBulkDueDate] = useState<Date | undefined>();
  const [bulkViolationType, setBulkViolationType] = useState("");
  const [bulkRequestedAction, setBulkRequestedAction] = useState("");
  const [bulkArticleSection, setBulkArticleSection] = useState("");
  const [bulkCitation, setBulkCitation] = useState("");
  const [expanded, setExpanded] = useState(false);

  // Violation types are scoped to the selected association only
  const [definedTypes, setDefinedTypes] = useState<any[]>([]);

  useEffect(() => {
    const fetchTypes = async () => {
      if (!associationId) {
        setDefinedTypes([]);
        return;
      }
      const { data } = await supabase
        .from("violation_types")
        .select("id, category, article_section, citation, requested_action")
        .eq("association_id", associationId)
        .order("category");
      setDefinedTypes(data || []);
    };
    fetchTypes();
    // Reset any previously chosen type when the association scope changes
    setBulkViolationType("");
  }, [associationId]);

  const handleDefinedTypeChange = (typeId: string) => {
    const dt = definedTypes.find((t: any) => t.id === typeId);
    if (dt) {
      setBulkViolationType(dt.category || "");
      if (dt.requested_action) setBulkRequestedAction(dt.requested_action);
      setBulkArticleSection(dt.article_section || "");
      setBulkCitation(dt.citation || "");
    }
  };

  const handleApply = async () => {
    const updates: Record<string, any> = {};
    if (bulkStatus) updates.status = bulkStatus;
    if (bulkStage) updates.stage = bulkStage;
    if (bulkPriority) updates.priority = bulkPriority;
    if (bulkViolationDate) updates.violation_date = format(bulkViolationDate, "yyyy-MM-dd");
    if (bulkDueDate) updates.due_date = format(bulkDueDate, "yyyy-MM-dd");
    if (bulkViolationType) {
      updates.violation_type = bulkViolationType;
      updates.title = bulkViolationType;
    }
    if (bulkRequestedAction) updates.description = bulkRequestedAction;

    if (Object.keys(updates).length === 0) {
      toast({ variant: "destructive", title: "No changes selected", description: "Pick at least one field to update." });
      return;
    }

    setLoading(true);
    try {
      const { error } = await supabase
        .from("violations")
        .update(updates)
        .in("id", selectedIds);
      if (error) throw error;

      // Persist article/citation/requested_action via notice_history entries
      // (violations table has no article_section/citation columns).
      if (bulkViolationType || bulkArticleSection || bulkCitation || bulkRequestedAction) {
        const { data: existing } = await supabase
          .from("violations")
          .select("id, notice_history, stage, status")
          .in("id", selectedIds);
        const timestamp = new Date().toISOString();
        await Promise.all((existing || []).map((v: any) => {
          const history = Array.isArray(v.notice_history) ? v.notice_history : [];
          const entry = {
            date: timestamp,
            status: v.status,
            notice_level: v.stage,
            violation_type: bulkViolationType || undefined,
            article_section: bulkArticleSection || undefined,
            citation: bulkCitation || undefined,
            requested_action: bulkRequestedAction || undefined,
            action: "Bulk Update",
          };
          return supabase
            .from("violations")
            .update({ notice_history: [...history, entry] })
            .eq("id", v.id);
        }));
      }
      toast({ title: `Updated ${selectedIds.length} violation(s)` });
      setBulkStatus("");
      setBulkStage("");
      setBulkPriority("");
      setBulkViolationDate(undefined);
      setBulkDueDate(undefined);
      setBulkViolationType("");
      setBulkRequestedAction("");
      setBulkArticleSection("");
      setBulkCitation("");
      onComplete();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Bulk update failed", description: err.message });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-3 bg-primary/5 border border-primary/20 rounded-lg space-y-2">
      <div className="flex items-center gap-2 flex-wrap">
        <div className="flex items-center gap-1.5 mr-2">
          <CheckCheck className="w-4 h-4 text-primary" />
          <span className="text-[13px] font-medium text-foreground">{selectedIds.length} selected</span>
        </div>

        <Select value={bulkStatus} onValueChange={setBulkStatus}>
          <SelectTrigger className="h-8 w-[140px] text-[12px]">
            <SelectValue placeholder="Set Status" />
          </SelectTrigger>
          <SelectContent>
            {STATUSES.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
          </SelectContent>
        </Select>

        <Select value={bulkStage} onValueChange={setBulkStage}>
          <SelectTrigger className="h-8 w-[140px] text-[12px]">
            <SelectValue placeholder="Set Stage" />
          </SelectTrigger>
          <SelectContent>
            {STAGES.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
          </SelectContent>
        </Select>

        <Select value={bulkPriority} onValueChange={setBulkPriority}>
          <SelectTrigger className="h-8 w-[140px] text-[12px]">
            <SelectValue placeholder="Set Priority" />
          </SelectTrigger>
          <SelectContent>
            {PRIORITIES.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
          </SelectContent>
        </Select>

        <Button variant="ghost" size="sm" className="h-8 text-[12px] gap-1" onClick={() => setExpanded(!expanded)}>
          {expanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
          {expanded ? "Less" : "More"}
        </Button>

        <Button size="sm" className="h-8 text-[12px] gap-1.5" onClick={handleApply} disabled={loading}>
          {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : null}
          Apply
        </Button>

        <Button variant="ghost" size="icon" className="h-8 w-8 ml-auto" onClick={onClear}>
          <X className="w-4 h-4" />
        </Button>
      </div>

      {expanded && (
        <div className="flex items-end gap-2 flex-wrap pt-1 border-t border-primary/10">
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" className={cn("h-8 w-[150px] text-[12px] justify-start font-normal", !bulkViolationDate && "text-muted-foreground")}>
                <CalendarIcon className="mr-1.5 h-3.5 w-3.5" />
                {bulkViolationDate ? format(bulkViolationDate, "MM/dd/yyyy") : "Violation Date"}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <Calendar mode="single" selected={bulkViolationDate} onSelect={setBulkViolationDate} initialFocus className={cn("p-3 pointer-events-auto")} />
            </PopoverContent>
          </Popover>

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" className={cn("h-8 w-[150px] text-[12px] justify-start font-normal", !bulkDueDate && "text-muted-foreground")}>
                <CalendarIcon className="mr-1.5 h-3.5 w-3.5" />
                {bulkDueDate ? format(bulkDueDate, "MM/dd/yyyy") : "Due Date"}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <Calendar mode="single" selected={bulkDueDate} onSelect={setBulkDueDate} initialFocus className={cn("p-3 pointer-events-auto")} />
            </PopoverContent>
          </Popover>

          {associationId ? (
            <div className="flex flex-col gap-1">
              <span className="text-[11px] text-muted-foreground">Violation Type</span>
              <Select
                value={bulkViolationType ? (definedTypes.find(d => d.category === bulkViolationType)?.id || "") : ""}
                onValueChange={handleDefinedTypeChange}
              >
                <SelectTrigger className="h-8 w-[220px] text-[12px]">
                  <SelectValue placeholder={definedTypes.length ? "Select violation type..." : "No types defined for this association"} />
                </SelectTrigger>
                <SelectContent>
                  {definedTypes.map((dt: any) => (
                    <SelectItem key={dt.id} value={dt.id}>
                      {dt.category}{dt.article_section ? ` (${dt.article_section})` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          ) : (
            <div className="flex flex-col gap-1">
              <span className="text-[11px] text-muted-foreground">Violation Type</span>
              <div className="h-8 px-3 flex items-center text-[12px] text-muted-foreground border border-dashed rounded-md w-[260px]">
                Filter by an association to choose a type
              </div>
            </div>
          )}

          <div className="flex flex-col gap-1 flex-1 min-w-[200px]">
            <span className="text-[11px] text-muted-foreground">Requested Action</span>
            <Textarea
              value={bulkRequestedAction}
              onChange={(e) => setBulkRequestedAction(e.target.value)}
              placeholder="Set requested action..."
              className="text-[12px] min-h-[32px] h-[32px] resize-none"
              rows={1}
            />
          </div>
        </div>
      )}
    </div>
  );
}
