import { useState, useEffect, useRef } from "react";
import { formatDateEST } from "@/lib/timezoneUtils";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FileText, Plus, Search, MoreHorizontal, Edit, Trash2, Paperclip, Upload, X, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import VotingAndComments from "@/components/shared/VotingAndComments";
import { useFileUpload } from "@/hooks/useFileUpload";

const statusColors: Record<string, string> = { open: "bg-blue-100 text-blue-700", "in-progress": "bg-amber-100 text-amber-700", resolved: "bg-emerald-100 text-emerald-700", closed: "bg-muted text-muted-foreground" };

const REQUEST_TYPES = [
  { value: "board_vote", label: "Board Vote" },
  { value: "vendor_quote", label: "Vendor Quote" },
  { value: "email_blast", label: "Community Email Blast" },
  { value: "violation", label: "Violation" },
  { value: "other", label: "Other" },
];
const requestTypeLabel = (v?: string | null) => REQUEST_TYPES.find((t) => t.value === v)?.label || "—";

type Attachment = { name: string; url: string; path: string; size: number; type: string };

const emptyForm = { title: "", description: "", status: "open", priority: "medium", requester_name: "", requester_email: "", request_type: "other" };

export default function ClientRequestsPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { toast } = useToast();
  const { uploadFiles, uploading } = useFileUpload();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [requests, setRequests] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [selectedRequest, setSelectedRequest] = useState<any>(null);
  const [form, setForm] = useState<typeof emptyForm & { association_id?: string }>(emptyForm);
  const [attachments, setAttachments] = useState<Attachment[]>([]);

  const isBoardView = !!boardAssociationIds?.length;

  const fetchData = async () => {
    setLoading(true);
    let query = supabase.from("client_requests").select("*, associations(name)").order("created_at", { ascending: false });
    let assocQuery = supabase.from("associations").select("id, name").eq("status", "active").order("name");
    if (isBoardView) query = query.in("association_id", boardAssociationIds!);
    if (isBoardView) assocQuery = assocQuery.in("id", boardAssociationIds!);
    const [{ data: reqs }, { data: assocs }] = await Promise.all([
      query,
      assocQuery,
    ]);
    setRequests(reqs || []);
    setAssociations(assocs || []);
    setLoading(false);
  };
  useEffect(() => { fetchData(); }, []);

  const openNew = async () => {
    setEditing(null);
    setAttachments([]);
    const { data: u } = await supabase.auth.getUser();
    const { data: profile } = u?.user ? await supabase.from("profiles").select("full_name").eq("user_id", u.user.id).single() : { data: null };
    setForm({
      ...emptyForm,
      requester_name: profile?.full_name || "",
      requester_email: u?.user?.email || "",
      association_id: associations[0]?.id,
    });
    setDialogOpen(true);
  };

  const openEdit = (r: any) => {
    setEditing(r);
    setAttachments(Array.isArray(r.attachments) ? r.attachments : []);
    setForm({
      title: r.title,
      description: r.description || "",
      status: r.status,
      priority: r.priority || "medium",
      requester_name: r.requester_name || "",
      requester_email: r.requester_email || "",
      request_type: r.request_type || "other",
      association_id: r.association_id,
    });
    setDialogOpen(true);
  };

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    const uploaded = await uploadFiles(files, "files", "client-requests");
    setAttachments((prev) => [...prev, ...uploaded as Attachment[]]);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const removeAttachment = (idx: number) => setAttachments((prev) => prev.filter((_, i) => i !== idx));

  const handleSave = async () => {
    if (!form.title.trim()) { toast({ variant: "destructive", title: "Title required" }); return; }
    if (!form.association_id) { toast({ variant: "destructive", title: "Association required" }); return; }
    setSaving(true);
    try {
      const payload = { ...form, attachments: attachments as any };
      if (editing) {
        const { error } = await supabase.from("client_requests").update(payload).eq("id", editing.id);
        if (error) throw error;
        toast({ title: "Request updated" });
      } else {
        const { error } = await supabase.from("client_requests").insert(payload as any);
        if (error) throw error;
        toast({ title: "Request submitted", description: "Admin and staff have been notified." });
      }
      setDialogOpen(false);
      fetchData();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Save failed", description: err.message });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    await supabase.from("client_requests").delete().eq("id", id);
    toast({ title: "Deleted" });
    fetchData();
  };

  const filtered = requests.filter((r) =>
    r.title.toLowerCase().includes(search.toLowerCase()) ||
    requestTypeLabel(r.request_type).toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2"><FileText className="h-6 w-6 text-primary" /> Client Requests</h1>
          <p className="text-sm text-muted-foreground mt-1">Submit and track client service requests.</p>
        </div>
        <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> New Request</Button>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input placeholder="Search by title or type..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No requests found.</CardContent></Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Requester</TableHead>
                <TableHead>Priority</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Files</TableHead>
                <TableHead>Date</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((r) => {
                const atts = Array.isArray(r.attachments) ? r.attachments : [];
                return (
                  <TableRow key={r.id} className="cursor-pointer" onClick={() => setSelectedRequest(r)}>
                    <TableCell className="font-medium">{r.title}</TableCell>
                    <TableCell><Badge variant="outline">{requestTypeLabel(r.request_type)}</Badge></TableCell>
                    <TableCell>{r.requester_name || "—"}</TableCell>
                    <TableCell className="capitalize">{r.priority}</TableCell>
                    <TableCell><Badge className={statusColors[r.status] || "bg-muted text-muted-foreground"}>{r.status}</Badge></TableCell>
                    <TableCell>{atts.length > 0 ? <span className="inline-flex items-center gap-1 text-muted-foreground"><Paperclip className="h-3.5 w-3.5" />{atts.length}</span> : "—"}</TableCell>
                    <TableCell>{formatDateEST(r.created_at)}</TableCell>
                    {!isBoardView && (
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => e.stopPropagation()}><MoreHorizontal className="h-4 w-4" /></Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={(e) => { e.stopPropagation(); openEdit(r); }}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem>
                            <DropdownMenuItem className="text-destructive" onClick={(e) => { e.stopPropagation(); handleDelete(r.id); }}><Trash2 className="h-4 w-4 mr-2" /> Delete</DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    )}
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Request" : "Submit a New Request"}</DialogTitle>
            <DialogDescription>
              {editing ? "Update the details below." : "Pick a request type, describe what you need, and attach any supporting files. Admin and staff will be notified."}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>Request Type *</Label>
                <Select value={form.request_type} onValueChange={(v) => setForm({ ...form, request_type: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {REQUEST_TYPES.map((t) => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Association *</Label>
                <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v })}>
                  <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                  <SelectContent>
                    {associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>Title *</Label>
              <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="Brief subject line" maxLength={200} />
            </div>

            <div>
              <Label>Description</Label>
              <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Provide details about your request..." rows={5} maxLength={2000} />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>Your Name</Label>
                <Input value={form.requester_name} onChange={(e) => setForm({ ...form, requester_name: e.target.value })} maxLength={100} />
              </div>
              <div>
                <Label>Your Email</Label>
                <Input type="email" value={form.requester_email} onChange={(e) => setForm({ ...form, requester_email: e.target.value })} maxLength={255} />
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>Priority</Label>
                <Select value={form.priority} onValueChange={(v) => setForm({ ...form, priority: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="low">Low</SelectItem>
                    <SelectItem value="medium">Medium</SelectItem>
                    <SelectItem value="high">High</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {editing && (
                <div>
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="open">Open</SelectItem>
                      <SelectItem value="in-progress">In Progress</SelectItem>
                      <SelectItem value="resolved">Resolved</SelectItem>
                      <SelectItem value="closed">Closed</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>

            {/* Attachments */}
            <div>
              <Label>Attachments</Label>
              <div className="mt-2 space-y-2">
                <input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileSelect} />
                <Button type="button" variant="outline" className="w-full gap-2" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
                  {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
                  {uploading ? "Uploading..." : "Add Files"}
                </Button>
                {attachments.length > 0 && (
                  <div className="space-y-1 rounded-md border p-2">
                    {attachments.map((a, i) => (
                      <div key={i} className="flex items-center justify-between gap-2 text-sm py-1 px-2 hover:bg-muted/50 rounded">
                        <a href={a.url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 text-primary hover:underline truncate">
                          <Paperclip className="h-3.5 w-3.5 shrink-0" />
                          <span className="truncate">{a.name}</span>
                        </a>
                        <Button type="button" variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => removeAttachment(i)}>
                          <X className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving || uploading}>
              {saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {editing ? "Update" : "Submit Request"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail/Vote Dialog */}
      <Dialog open={!!selectedRequest} onOpenChange={(open) => !open && setSelectedRequest(null)}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><FileText className="w-5 h-5" /> Request Details</DialogTitle></DialogHeader>
          {selectedRequest && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><p className="text-sm text-muted-foreground">Title</p><p className="font-medium">{selectedRequest.title}</p></div>
                <div><p className="text-sm text-muted-foreground">Type</p><Badge variant="outline">{requestTypeLabel(selectedRequest.request_type)}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Status</p><Badge className={statusColors[selectedRequest.status] || ""}>{selectedRequest.status}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Priority</p><p className="font-medium capitalize">{selectedRequest.priority}</p></div>
                <div><p className="text-sm text-muted-foreground">Requester</p><p className="font-medium">{selectedRequest.requester_name || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Email</p><p className="font-medium">{selectedRequest.requester_email || "—"}</p></div>
              </div>
              {selectedRequest.description && (
                <div><p className="text-sm text-muted-foreground">Description</p><p className="bg-muted p-3 rounded-md mt-1 border whitespace-pre-wrap">{selectedRequest.description}</p></div>
              )}
              {Array.isArray(selectedRequest.attachments) && selectedRequest.attachments.length > 0 && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">Attachments</p>
                  <div className="space-y-1 rounded-md border p-2">
                    {selectedRequest.attachments.map((a: Attachment, i: number) => (
                      <a key={i} href={a.url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 text-sm text-primary hover:underline py-1 px-2 hover:bg-muted/50 rounded">
                        <Paperclip className="h-3.5 w-3.5 shrink-0" />
                        <span className="truncate">{a.name}</span>
                      </a>
                    ))}
                  </div>
                </div>
              )}
              <VotingAndComments entityType="client_request" entityId={selectedRequest.id} />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
