import { useState } from "react";
import { Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Loader2, Upload } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/use-auth";
import { signedUrl, uploadToBucket } from "@/lib/storage";

type ReportRow = {
  id: string;
  user_id: string;
  reference: string;
  inspection_date: string;
  inspector_name: string;
  property_info: string | null;
  severity: string | null;
  treatment_performed: string | null;
  inspector_comments: string | null;
  ai_assessment: string | null;
  recommendations: string[];
  published: boolean;
};

const emptyDraft = {
  booking_id: "",
  inspector_name: "",
  inspection_date: new Date().toISOString().slice(0, 10),
  property_info: "",
  severity: "Low",
  treatment_performed: "",
  inspector_comments: "",
  ai_assessment: "",
  recommendations: "",
};

export function ReportsAdmin() {
  const { user } = useAuth();
  const qc = useQueryClient();
  const [draft, setDraft] = useState(emptyDraft);
  const [creating, setCreating] = useState(false);
  const [openId, setOpenId] = useState<string | null>(null);

  const bookings = useQuery({
    queryKey: ["admin-bookings-for-reports"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("bookings")
        .select("id,user_id,full_name,service_name,address,preferred_date")
        .order("created_at", { ascending: false })
        .limit(100);
      if (error) throw error;
      return data;
    },
  });

  const reports = useQuery({
    queryKey: ["admin-reports-full"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("inspection_reports")
        .select("*")
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data as ReportRow[];
    },
  });

  const refresh = () => qc.invalidateQueries({ queryKey: ["admin-reports-full"] });

  async function createReport() {
    const booking = bookings.data?.find((b) => b.id === draft.booking_id);
    if (!booking?.user_id) return toast.error("Choose a booking with a registered customer.");
    if (!draft.inspector_name.trim()) return toast.error("Enter the inspector name.");
    setCreating(true);
    const { error } = await supabase.from("inspection_reports").insert({
      user_id: booking.user_id,
      booking_id: booking.id,
      inspector_name: draft.inspector_name.trim(),
      inspection_date: draft.inspection_date,
      property_info: draft.property_info || booking.address,
      severity: draft.severity,
      treatment_performed: draft.treatment_performed || null,
      inspector_comments: draft.inspector_comments || null,
      ai_assessment: draft.ai_assessment || null,
      recommendations: draft.recommendations.split("\n").map((r) => r.trim()).filter(Boolean),
      published: false,
    });
    setCreating(false);
    if (error) return toast.error("Could not create the report.");
    toast.success("Draft report created.");
    setDraft(emptyDraft);
    refresh();
  }

  return (
    <div className="mt-4 space-y-4">
      <section className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
        <h2 className="text-sm font-semibold">New inspection report</h2>
        <div className="mt-3 grid gap-2">
          <select
            aria-label="Booking"
            value={draft.booking_id}
            onChange={(e) => setDraft({ ...draft, booking_id: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          >
            <option value="">Select a booking…</option>
            {bookings.data?.map((b) => (
              <option key={b.id} value={b.id}>
                {b.full_name} — {b.service_name} ({b.preferred_date ?? "no date"})
              </option>
            ))}
          </select>
          <input
            placeholder="Inspector name"
            value={draft.inspector_name}
            onChange={(e) => setDraft({ ...draft, inspector_name: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <input
            type="date"
            aria-label="Inspection date"
            value={draft.inspection_date}
            onChange={(e) => setDraft({ ...draft, inspection_date: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <input
            placeholder="Property information"
            value={draft.property_info}
            onChange={(e) => setDraft({ ...draft, property_info: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <select
            aria-label="Severity"
            value={draft.severity}
            onChange={(e) => setDraft({ ...draft, severity: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          >
            {["Low", "Medium", "High"].map((s) => (
              <option key={s} value={s}>
                {s} severity
              </option>
            ))}
          </select>
          <textarea
            rows={2}
            placeholder="AI assessment summary"
            value={draft.ai_assessment}
            onChange={(e) => setDraft({ ...draft, ai_assessment: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <textarea
            rows={2}
            placeholder="Treatment performed"
            value={draft.treatment_performed}
            onChange={(e) => setDraft({ ...draft, treatment_performed: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <textarea
            rows={2}
            placeholder="Inspector comments"
            value={draft.inspector_comments}
            onChange={(e) => setDraft({ ...draft, inspector_comments: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <textarea
            rows={3}
            placeholder="Recommendations (one per line)"
            value={draft.recommendations}
            onChange={(e) => setDraft({ ...draft, recommendations: e.target.value })}
            className="rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <button
            onClick={createReport}
            disabled={creating}
            className="flex items-center justify-center gap-2 rounded-xl bg-brand py-2.5 text-xs font-semibold text-primary-foreground disabled:opacity-50"
          >
            {creating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null} Create draft report
          </button>
        </div>
      </section>

      {reports.data?.map((r) => (
        <ReportEditor
          key={r.id}
          report={r}
          open={openId === r.id}
          onToggle={() => setOpenId(openId === r.id ? null : r.id)}
          onChanged={refresh}
          adminId={user?.id}
        />
      ))}
      {reports.data?.length === 0 ? <p className="text-sm text-muted-foreground">No reports yet.</p> : null}
    </div>
  );
}

function ReportEditor({
  report,
  open,
  onToggle,
  onChanged,
}: {
  report: ReportRow;
  open: boolean;
  onToggle: () => void;
  onChanged: () => void;
  adminId?: string;
}) {
  const qc = useQueryClient();
  const [comments, setComments] = useState(report.inspector_comments ?? "");
  const [busy, setBusy] = useState(false);

  const photos = useQuery({
    queryKey: ["report-photos", report.id],
    enabled: open,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("report_photos")
        .select("*")
        .eq("report_id", report.id)
        .order("created_at");
      if (error) throw error;
      return Promise.all(
        data.map(async (p) => ({ ...p, view: await signedUrl(p.url) })),
      );
    },
  });

  async function upload(file: File, kind: "before" | "after") {
    setBusy(true);
    try {
      const path = await uploadToBucket(file, "reports", report.user_id);
      const { error } = await supabase.from("report_photos").insert({ report_id: report.id, url: path, kind });
      if (error) throw error;
      qc.invalidateQueries({ queryKey: ["report-photos", report.id] });
      toast.success(`${kind === "before" ? "Before" : "After"} photo added.`);
    } catch {
      toast.error("Upload failed.");
    } finally {
      setBusy(false);
    }
  }

  async function save(patch: Partial<ReportRow>) {
    const { error } = await supabase.from("inspection_reports").update(patch).eq("id", report.id);
    if (error) return toast.error("Could not save the report.");
    toast.success("Report updated.");
    onChanged();
  }

  return (
    <article className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
      <button onClick={onToggle} className="flex w-full items-start justify-between gap-3 text-left">
        <span>
          <span className="block text-sm font-semibold">{report.reference}</span>
          <span className="block text-xs text-muted-foreground">
            {report.inspector_name} • {report.inspection_date} • {report.severity ?? "—"}
          </span>
        </span>
        <span
          className={`shrink-0 rounded-full px-2.5 py-1 text-[11px] font-semibold ${
            report.published ? "bg-success/15" : "bg-muted text-muted-foreground"
          }`}
        >
          {report.published ? "Published" : "Draft"}
        </span>
      </button>

      {open ? (
        <div className="mt-3 border-t border-border/60 pt-3">
          <label className="block text-[11px] text-muted-foreground" htmlFor={`c-${report.id}`}>
            Inspector comments
          </label>
          <textarea
            id={`c-${report.id}`}
            rows={3}
            value={comments}
            onChange={(e) => setComments(e.target.value)}
            className="mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-xs"
          />
          <button
            onClick={() => save({ inspector_comments: comments })}
            className="mt-2 rounded-xl border border-border px-3 py-1.5 text-[11px] font-semibold"
          >
            Save comments
          </button>

          <div className="mt-4 grid grid-cols-2 gap-3">
            {(["before", "after"] as const).map((kind) => (
              <div key={kind}>
                <p className="text-[11px] font-semibold uppercase tracking-widest text-primary">{kind}</p>
                <div className="mt-1 space-y-2">
                  {photos.data
                    ?.filter((p) => p.kind === kind)
                    .map((p) => (
                      <img key={p.id} src={p.view ?? ""} alt={`${kind} photo`} className="w-full rounded-xl" />
                    ))}
                </div>
                <label className="mt-2 flex cursor-pointer items-center justify-center gap-1.5 rounded-xl border border-border py-2 text-[11px] font-semibold">
                  <Upload className="h-3.5 w-3.5" /> Add {kind}
                  <input
                    type="file"
                    accept="image/*"
                    hidden
                    disabled={busy}
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (f) upload(f, kind);
                    }}
                  />
                </label>
              </div>
            ))}
          </div>

          <div className="mt-4 grid grid-cols-2 gap-2">
            <button
              onClick={() => save({ published: !report.published })}
              className="rounded-xl bg-brand py-2 text-xs font-semibold text-primary-foreground"
            >
              {report.published ? "Unpublish" : "Publish to customer"}
            </button>
            <Link
              to="/reports/$id"
              params={{ id: report.id }}
              className="rounded-xl border border-border py-2 text-center text-xs font-semibold"
            >
              Preview report
            </Link>
          </div>
        </div>
      ) : null}
    </article>
  );
}