import { useState, useEffect, useCallback } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { AlertTriangle, CheckCircle2, Loader2, Send, ShieldAlert, Calendar, MapPin, ImagePlus, X } from "lucide-react";
import { formatDateLongEST } from "@/lib/timezoneUtils";
import { useDropzone } from "react-dropzone";
import acmLogo from "@/assets/acm-logo.png";

export default function ViolationResponsePage() {
  const { id } = useParams<{ id: string }>();
  const [violation, setViolation] = useState<any>(null);
  const [association, setAssociation] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  

  // Response form state
  const [respondentName, setRespondentName] = useState("");
  const [respondentEmail, setRespondentEmail] = useState("");
  const [respondentPhone, setRespondentPhone] = useState("");
  const [responseText, setResponseText] = useState("");
  const [dateCorrected, setDateCorrected] = useState("");
  const [photoFiles, setPhotoFiles] = useState<File[]>([]);
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([]);

  useEffect(() => {
    if (!id) return;
    const fetchViolation = async () => {
      setLoading(true);
      
      // Use secure RPC to fetch only non-PII violation fields
      const { data: violations, error: violationError } = await supabase
        .rpc("lookup_violation_for_response", { p_violation_id: id });
      const violationData = violations?.[0] || null;

      if (violationError || !violationData) {
        setError("This violation link is invalid or has expired.");
        setLoading(false);
        return;
      }

      // Fetch related data separately, ignoring RLS errors for anon users
      let assocData = null;
      let unitData = null;
      let ownerData = null;

      if (violationData.association_id) {
        const { data } = await supabase
          .from("associations")
          .select("name, address, city, state, zip, phone, email")
          .eq("id", violationData.association_id)
          .maybeSingle();
        assocData = data;
      }

      if (violationData.unit_id) {
        const { data } = await supabase
          .from("units")
          .select("unit_number, address, city, state, zip")
          .eq("id", violationData.unit_id)
          .maybeSingle();
        unitData = data;
      }

      if (violationData.owner_id) {
        const { data } = await supabase
          .from("owners")
          .select("id, first_name, last_name, email, phone, property_address, street_address, mailing_address")
          .eq("id", violationData.owner_id)
          .maybeSingle();
        ownerData = data;
      }

      const fullData = {
        ...violationData,
        associations: assocData,
        units: unitData,
        owners: ownerData,
      };

      setViolation(fullData);
      setAssociation(assocData);

      // Pre-populate from the violation's linked owner
      if (ownerData) {
        const fullName = [ownerData.first_name, ownerData.last_name].filter(Boolean).join(" ");
        setRespondentName(fullName);
        if (ownerData.email) setRespondentEmail(ownerData.email);
        if (ownerData.phone) setRespondentPhone(ownerData.phone);
      }

      setLoading(false);
    };
    fetchViolation();
  }, [id]);


  // Photo handling
  const onDrop = useCallback((accepted: File[]) => {
    const newFiles = [...photoFiles, ...accepted].slice(0, 10);
    setPhotoFiles(newFiles);
    setPhotoPreviews(newFiles.map(f => URL.createObjectURL(f)));
  }, [photoFiles]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: { "image/*": [".jpg", ".jpeg", ".png", ".webp", ".heic"] },
    maxSize: 10 * 1024 * 1024,
    maxFiles: 10,
  });

  const removePhoto = (index: number) => {
    URL.revokeObjectURL(photoPreviews[index]);
    setPhotoFiles(prev => prev.filter((_, i) => i !== index));
    setPhotoPreviews(prev => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!id) return;
    setSubmitting(true);
    setError(null);

    try {
      // Upload photos first
      const uploadedUrls: string[] = [];
      for (const file of photoFiles) {
        const path = `responses/${id}/${Date.now()}-${file.name}`;
        const { error: uploadErr } = await supabase.storage.from("violation-photos").upload(path, file, { contentType: file.type });
        if (uploadErr) throw uploadErr;
        const { data: urlData } = supabase.storage.from("violation-photos").getPublicUrl(path);
        uploadedUrls.push(urlData.publicUrl);
      }

      const { error: insertError } = await supabase.from("violation_responses").insert({
        violation_id: id,
        respondent_name: respondentName || null,
        respondent_email: respondentEmail || null,
        respondent_phone: respondentPhone || null,
        response_text: responseText || null,
        date_corrected: dateCorrected || null,
        photo_urls: uploadedUrls.length > 0 ? uploadedUrls : null,
      });

      if (insertError) throw insertError;
      setSubmitted(true);
    } catch (err: any) {
      console.error("Submit error:", err);
      setError("Failed to submit response. Please try again.");
    }
    setSubmitting(false);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-muted to-muted/50">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error && !violation) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-muted to-muted/50 p-4">
        <Card className="max-w-md w-full text-center">
          <CardContent className="pt-8 pb-8 space-y-4">
            <AlertTriangle className="w-12 h-12 text-destructive mx-auto" />
            <h2 className="text-xl font-bold">Invalid Link</h2>
            <p className="text-muted-foreground">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-muted to-muted/50 p-4">
        <Card className="max-w-md w-full text-center">
          <CardContent className="pt-8 pb-8 space-y-4">
            <CheckCircle2 className="w-14 h-14 text-primary mx-auto" />
            <h2 className="text-xl font-bold">Response Submitted</h2>
            <p className="text-muted-foreground">
              Thank you for your response. The management team has been notified and will review your submission.
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  const statusColor = (s: string | null) => {
    switch ((s || "").toLowerCase()) {
      case "open": return "destructive" as const;
      case "resolved": case "closed": return "default" as const;
      default: return "secondary" as const;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-muted to-muted/50">
      {/* Header */}
      <div className="bg-foreground text-background">
        <div className="max-w-2xl mx-auto px-4 py-5 flex items-center gap-4">
          <img src={acmLogo} alt="Logo" className="h-10 w-auto rounded bg-white p-1" />
          <div>
            <h1 className="text-lg font-bold">{association?.name || "Community Association"}</h1>
            <p className="text-sm text-white/70">Violation Response Portal</p>
          </div>
        </div>
      </div>

      <div className="max-w-2xl mx-auto px-4 py-8 space-y-6">
        {/* Violation Summary */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-2">
                <ShieldAlert className="w-5 h-5 text-destructive" />
                <CardTitle className="text-base">Violation Notice</CardTitle>
              </div>
              <Badge variant={statusColor(violation.status)}>{violation.status || "Open"}</Badge>
            </div>
            <CardDescription className="text-xs mt-1">
              ID: V-{String(violation.id).substring(0, 8).toUpperCase()}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Owner & Address Info */}
            {violation.owners && (
              <div className="bg-muted/50 rounded-lg p-3 border space-y-1">
                <p className="text-xs text-muted-foreground font-medium">Property Owner</p>
                <p className="text-sm font-semibold">
                  {[violation.owners.first_name, violation.owners.last_name].filter(Boolean).join(" ")}
                </p>
                {(() => {
                  const unit = violation.units;
                  const owner = violation.owners;
                  const address = unit?.address || owner?.property_address || owner?.street_address || owner?.mailing_address;
                  const city = unit?.city;
                  const state = unit?.state;
                  const zip = unit?.zip;
                  const cityStateZip = [city, state].filter(Boolean).join(", ") + (zip ? ` ${zip}` : "");
                  return address ? (
                    <div className="flex items-start gap-1.5">
                      <MapPin className="w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0" />
                      <p className="text-sm text-muted-foreground">
                        {address}{cityStateZip ? `, ${cityStateZip}` : ""}
                      </p>
                    </div>
                  ) : null;
                })()}
              </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-0.5">
                <p className="text-xs text-muted-foreground font-medium">Violation Type</p>
                <p className="text-sm font-medium">{violation.title || violation.category || "General"}</p>
              </div>
              {violation.units?.unit_number && (
                <div className="space-y-0.5 flex items-start gap-1.5">
                  <MapPin className="w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0" />
                  <div>
                    <p className="text-xs text-muted-foreground font-medium">Unit</p>
                    <p className="text-sm">{violation.units.unit_number}</p>
                  </div>
                </div>
              )}
              <div className="space-y-0.5 flex items-start gap-1.5">
                <Calendar className="w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0" />
                <div>
                  <p className="text-xs text-muted-foreground font-medium">Date Issued</p>
                  <p className="text-sm">{formatDateLongEST(violation.created_at)}</p>
                </div>
              </div>
              {violation.due_date && (
                <div className="space-y-0.5 flex items-start gap-1.5">
                  <Calendar className="w-3.5 h-3.5 text-destructive mt-0.5 shrink-0" />
                  <div>
                    <p className="text-xs text-muted-foreground font-medium">Due Date</p>
                    <p className="text-sm font-medium text-destructive">{formatDateLongEST(violation.due_date)}</p>
                  </div>
                </div>
              )}
            </div>

            {violation.description && (
              <>
                <Separator />
                <div>
                  <p className="text-xs text-muted-foreground font-medium mb-1">Description</p>
                  <p className="text-sm bg-muted/50 rounded-md p-3 border">{violation.description}</p>
                </div>
              </>
            )}
          </CardContent>
        </Card>

        {/* Response Form */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <Send className="w-4 h-4" /> Submit Your Response
            </CardTitle>
            <CardDescription className="text-xs">
              Please provide your information and any details about steps taken to resolve this violation.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <Label className="text-xs">Your Name *</Label>
                  <Input
                    value={respondentName}
                    onChange={(e) => setRespondentName(e.target.value)}
                    placeholder="Your full name"
                    className="text-sm"
                    readOnly={!!violation?.owners}
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Email</Label>
                  <Input
                    type="email"
                    value={respondentEmail}
                    onChange={(e) => setRespondentEmail(e.target.value)}
                    placeholder="you@example.com"
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Phone</Label>
                  <Input
                    type="tel"
                    value={respondentPhone}
                    onChange={(e) => setRespondentPhone(e.target.value)}
                    placeholder="(555) 123-4567"
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Date Corrected</Label>
                  <Input
                    type="date"
                    value={dateCorrected}
                    onChange={(e) => setDateCorrected(e.target.value)}
                    className="text-sm"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <Label className="text-xs">Response / Comments *</Label>
                <Textarea
                  value={responseText}
                  onChange={(e) => setResponseText(e.target.value)}
                  placeholder="Describe the steps you've taken or plan to take to resolve this violation..."
                  className="text-sm min-h-[120px]"
                  required
                />
              </div>

              {/* Photo Upload */}
              <div className="space-y-1.5">
                <Label className="text-xs">Photos (optional, up to 10)</Label>
                <div
                  {...getRootProps()}
                  className={`rounded-lg border-2 border-dashed p-4 text-center cursor-pointer transition-colors ${
                    isDragActive ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/30"
                  }`}
                >
                  <input {...getInputProps()} />
                  <ImagePlus className="w-8 h-8 mx-auto text-muted-foreground/40 mb-2" />
                  <p className="text-xs text-muted-foreground">
                    {isDragActive ? "Drop photos here..." : "Drag & drop photos or click to browse"}
                  </p>
                  <p className="text-[10px] text-muted-foreground/60 mt-1">JPG, PNG, WEBP — max 10MB each</p>
                </div>

                {photoPreviews.length > 0 && (
                  <div className="grid grid-cols-3 sm:grid-cols-5 gap-2 mt-2">
                    {photoPreviews.map((url, i) => (
                      <div key={i} className="relative group rounded-md overflow-hidden border bg-muted aspect-square">
                        <img src={url} alt={`Upload ${i + 1}`} className="w-full h-full object-cover" />
                        <button
                          type="button"
                          onClick={() => removePhoto(i)}
                          className="absolute top-1 right-1 bg-background/80 rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          <X className="w-3.5 h-3.5 text-destructive" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {error && (
                <p className="text-sm text-destructive">{error}</p>
              )}

              <Button type="submit" className="w-full gap-2" disabled={submitting}>
                {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                {submitting ? "Submitting..." : "Submit Response"}
              </Button>
            </form>
          </CardContent>
        </Card>

        <p className="text-center text-xs text-muted-foreground pb-4">
          This is a secure response portal. Your information is encrypted and only shared with the association management team.
        </p>
      </div>
    </div>
  );
}
