"use client";

import { useMemo, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Kpi, KpiStrip } from "@/components/ui/kpi";
import { EmptyState } from "@/components/ui/empty-state";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useToast } from "@/components/ui/toast";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency } from "@/lib/utils";
import { snapshotForAgentCall } from "@/lib/agents/context-snapshot";

type EmploymentType = "Full-time" | "Part-time" | "Contract" | "Internship" | "Temporary";
type JobStatus = "Draft" | "Posted" | "Interviewing" | "Filled" | "Cancelled";

interface JobOpening {
  id: string;
  organizationSlug: string;
  title: string;
  employmentType: EmploymentType;
  status: JobStatus;
  location: string;
  compMin?: number;
  compMax?: number;
  compType?: "salary" | "hourly";
  description?: string;
  qualifications?: string;
  indeedDraft?: string;
  postedDate?: string;
  filledDate?: string;
  applicantCount?: number;
  indeedJobId?: string;
  notes?: string;
  createdAt: string;
}

export function HiringBoard() {
  const [jobs, setJobs] = useLocalStorage<JobOpening[]>("sag.hiring.jobs", []);
  const [showAdd, setShowAdd] = useState(false);
  const [filterStatus, setFilterStatus] = useState<JobStatus | "all">("all");
  const [filterEntity, setFilterEntity] = useState<string>("all");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [drafting, setDrafting] = useState<string | null>(null);
  const { toast } = useToast();
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const filtered = useMemo(
    () =>
      jobs.filter((j) => {
        if (filterStatus !== "all" && j.status !== filterStatus) return false;
        if (filterEntity !== "all" && j.organizationSlug !== filterEntity) return false;
        return true;
      }),
    [jobs, filterStatus, filterEntity]
  );

  const stats = useMemo(
    () => ({
      total: jobs.length,
      posted: jobs.filter((j) => j.status === "Posted" || j.status === "Interviewing").length,
      filled: jobs.filter((j) => j.status === "Filled").length,
      applicants: jobs.reduce((sum, j) => sum + (j.applicantCount ?? 0), 0),
    }),
    [jobs]
  );

  function addJob(j: Omit<JobOpening, "id" | "createdAt">) {
    setJobs([{ ...j, id: `job-${Date.now()}`, createdAt: new Date().toISOString() }, ...jobs]);
    setShowAdd(false);
  }

  function updateJob(id: string, patch: Partial<JobOpening>) {
    setJobs(jobs.map((j) => (j.id === id ? { ...j, ...patch } : j)));
  }

  async function deleteJob(id: string) {
    const ok = await confirmAlert({
      title: "Delete this job opening?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    setJobs(jobs.filter((j) => j.id !== id));
  }

  async function generateDraft(job: JobOpening) {
    setDrafting(job.id);
    try {
      const org = ALL_ORGANIZATIONS.find((o) => o.slug === job.organizationSlug);
      const prompt = `Draft an Indeed-ready job posting for a SAG portfolio company.

Hiring entity: ${org?.name ?? job.organizationSlug} (${org?.industry}) — a wholly-owned C-corp subsidiary of South Armz Global, Inc., headquartered in ${org?.state ?? "NC"}.

Role: ${job.title}
Employment type: ${job.employmentType}
Location: ${job.location}
Compensation: ${job.compType === "salary" ? `$${job.compMin?.toLocaleString()} – $${job.compMax?.toLocaleString()} annual` : job.compType === "hourly" ? `$${job.compMin} – $${job.compMax}/hr` : "Negotiable"}

Existing description draft: ${job.description ?? "(none — generate from scratch)"}
Existing qualifications: ${job.qualifications ?? "(generate appropriate ones)"}

Return a complete Indeed job posting with:
1. Compelling hook (1-2 sentences about ${org?.name})
2. Role overview (what they do day-to-day)
3. Responsibilities (5-7 bullets)
4. Qualifications (must-haves + nice-to-haves)
5. Compensation + benefits summary
6. NC at-will employment + equal-opportunity boilerplate
7. How to apply

~400-500 words. Tone: friendly, direct, NC-rooted. Skip corporate-speak.`;

      const resp = await fetch("/api/agents/hr", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          messages: [{ role: "user", content: prompt }],
          contextSnapshot: snapshotForAgentCall(),
        }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || "Draft failed");
      updateJob(job.id, { indeedDraft: data.message });
    } catch (e) {
      alert("Draft failed: " + (e instanceof Error ? e.message : "unknown"));
    } finally {
      setDrafting(null);
    }
  }

  function copyDraft(draft: string) {
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      navigator.clipboard.writeText(draft);
      toast({
        title: "Copied to clipboard",
        description: "Paste into Indeed at employers.indeed.com/p/post-job",
        variant: "success",
      });
    }
  }

  return (
    <>
    <div className="space-y-6">
      <Card>
        <CardContent className="p-5">
          <div className="flex items-start justify-between flex-wrap gap-3">
            <div>
              <h2 className="text-base font-semibold">Indeed posting workflow</h2>
              <p className="text-sm text-muted-foreground mt-1 max-w-2xl">
                Draft job specs here per entity, hand them to the HR Agent for an Indeed-ready posting, then copy-paste into the Indeed employer dashboard. Free postings cycle into Sponsored visibility after a few days.
              </p>
            </div>
            <div className="flex gap-2 flex-wrap">
              <Button asChild variant="outline" size="sm">
                <a href="https://employers.indeed.com" target="_blank" rel="noopener noreferrer">Indeed dashboard ↗</a>
              </Button>
              <Button asChild variant="outline" size="sm">
                <a href="https://employers.indeed.com/p/post-job" target="_blank" rel="noopener noreferrer">Post a job ↗</a>
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <KpiStrip cols={4}>
        <Kpi label="Total roles" value={String(stats.total)} />
        <Kpi label="Active" value={String(stats.posted)} tone="violet" />
        <Kpi label="Filled" value={String(stats.filled)} tone="emerald" />
        <Kpi label="Applicants" value={String(stats.applicants)} />
      </KpiStrip>

      <Card>
        <CardContent className="p-4 flex flex-wrap items-center gap-3">
          <select
            value={filterEntity}
            onChange={(e) => setFilterEntity(e.target.value)}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All entities</option>
            {ALL_ORGANIZATIONS.map((o) => (
              <option key={o.slug} value={o.slug}>{o.emoji} {o.name}</option>
            ))}
          </select>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value as JobStatus | "all")}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All statuses</option>
            <option value="Draft">Draft</option>
            <option value="Posted">Posted</option>
            <option value="Interviewing">Interviewing</option>
            <option value="Filled">Filled</option>
            <option value="Cancelled">Cancelled</option>
          </select>
          <span className="text-xs text-muted-foreground tabular-nums">
            {filtered.length} of {jobs.length}
          </span>
          <Button variant="brand" size="sm" className="ml-auto" onClick={() => setShowAdd((v) => !v)}>
            {showAdd ? "Cancel" : "+ Open a role"}
          </Button>
        </CardContent>
      </Card>

      {showAdd && <AddJobForm onAdd={addJob} onCancel={() => setShowAdd(false)} />}

      {filtered.length === 0 ? (
        <EmptyState
          icon="📣"
          title="No openings tracked yet"
          description="Open a role above. The HR Agent will draft an Indeed posting from your inputs and the entity’s brand voice."
        />
      ) : (
        <div className="space-y-3">
          {filtered.map((j) => {
            const org = ALL_ORGANIZATIONS.find((o) => o.slug === j.organizationSlug);
            const expanded = expandedId === j.id;
            return (
              <Card key={j.id}>
                <CardContent className="p-5">
                  <div className="flex items-start justify-between gap-3 flex-wrap">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 flex-wrap mb-1">
                        <Badge
                          variant={
                            j.status === "Filled" ? "success" : j.status === "Posted" || j.status === "Interviewing" ? "info" : j.status === "Cancelled" ? "destructive" : "outline"
                          }
                          className="text-[10px]"
                        >
                          {j.status}
                        </Badge>
                        <Badge variant="outline" className="text-[10px]">{j.employmentType}</Badge>
                        <span className="text-xs text-muted-foreground inline-flex items-center gap-1">
                          {org?.emoji} {org?.name}
                        </span>
                      </div>
                      <h3 className="text-base font-semibold">{j.title}</h3>
                      <div className="mt-1 text-xs text-muted-foreground space-x-3">
                        <span>📍 {j.location}</span>
                        {j.compMin != null && (
                          <span>
                            💵 {j.compType === "salary"
                              ? `${formatCurrency(j.compMin)}–${formatCurrency(j.compMax ?? j.compMin)}/yr`
                              : `${formatCurrency(j.compMin)}–${formatCurrency(j.compMax ?? j.compMin)}/hr`}
                          </span>
                        )}
                        {j.applicantCount != null && j.applicantCount > 0 && <span>👥 {j.applicantCount} applicants</span>}
                      </div>
                    </div>
                    <div className="flex items-center gap-1 shrink-0 flex-wrap">
                      <select
                        value={j.status}
                        onChange={(e) => updateJob(j.id, { status: e.target.value as JobStatus })}
                        className="h-8 rounded-md border border-input bg-background px-2 text-xs"
                      >
                        <option value="Draft">Draft</option>
                        <option value="Posted">Posted</option>
                        <option value="Interviewing">Interviewing</option>
                        <option value="Filled">Filled</option>
                        <option value="Cancelled">Cancelled</option>
                      </select>
                      <Button variant="ghost" size="sm" onClick={() => setExpandedId(expanded ? null : j.id)}>
                        {expanded ? "Close" : "Details"}
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => deleteJob(j.id)}>×</Button>
                    </div>
                  </div>

                  {expanded && (
                    <div className="mt-5 space-y-4">
                      <div className="grid gap-3 md:grid-cols-2">
                        <Field label="Description">
                          <textarea
                            className="mt-1 w-full text-sm rounded-md border border-input bg-background p-2"
                            rows={3}
                            value={j.description ?? ""}
                            onChange={(e) => updateJob(j.id, { description: e.target.value })}
                            placeholder="What does this role actually do?"
                          />
                        </Field>
                        <Field label="Qualifications">
                          <textarea
                            className="mt-1 w-full text-sm rounded-md border border-input bg-background p-2"
                            rows={3}
                            value={j.qualifications ?? ""}
                            onChange={(e) => updateJob(j.id, { qualifications: e.target.value })}
                            placeholder="Must-haves + nice-to-haves"
                          />
                        </Field>
                        <Field label="Indeed Job ID (after posting)">
                          <Input
                            value={j.indeedJobId ?? ""}
                            onChange={(e) => updateJob(j.id, { indeedJobId: e.target.value })}
                            placeholder="e.g. abc123xyz from indeed URL"
                          />
                        </Field>
                        <Field label="Applicants count">
                          <Input
                            type="number"
                            value={j.applicantCount ?? ""}
                            onChange={(e) => updateJob(j.id, { applicantCount: parseInt(e.target.value || "0", 10) || undefined })}
                          />
                        </Field>
                        <Field label="Notes" className="md:col-span-2">
                          <textarea
                            className="mt-1 w-full text-sm rounded-md border border-input bg-background p-2"
                            rows={2}
                            value={j.notes ?? ""}
                            onChange={(e) => updateJob(j.id, { notes: e.target.value })}
                            placeholder="Interview pipeline, top candidates, etc."
                          />
                        </Field>
                      </div>

                      <div className="border-t pt-4">
                        <div className="flex items-center justify-between mb-2 flex-wrap gap-2">
                          <h4 className="text-sm font-semibold">Indeed-ready posting (HR Agent draft)</h4>
                          <div className="flex gap-2">
                            <Button
                              variant="brand"
                              size="sm"
                              disabled={drafting === j.id}
                              onClick={() => generateDraft(j)}
                            >
                              {drafting === j.id ? "Drafting..." : j.indeedDraft ? "Regenerate" : "Generate with HR Agent"}
                            </Button>
                            {j.indeedDraft && (
                              <Button variant="outline" size="sm" onClick={() => copyDraft(j.indeedDraft!)}>
                                Copy
                              </Button>
                            )}
                            {j.indeedDraft && (
                              <Button asChild variant="outline" size="sm">
                                <a href="https://employers.indeed.com/p/post-job" target="_blank" rel="noopener noreferrer">
                                  Paste in Indeed ↗
                                </a>
                              </Button>
                            )}
                          </div>
                        </div>
                        {j.indeedDraft ? (
                          <pre className="whitespace-pre-wrap text-xs font-sans leading-relaxed bg-muted rounded-md p-3 max-h-[40vh] overflow-y-auto">
                            {j.indeedDraft}
                          </pre>
                        ) : (
                          <p className="text-xs text-muted-foreground">
                            Click <strong>Generate with HR Agent</strong> to draft a complete Indeed posting using this entity’s brand voice, the role details above, and NC labor-law standards.
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      <p className="text-xs text-muted-foreground">
        Indeed API integration requires partner approval and isn’t enabled by default. Today’s workflow: draft here, copy to Indeed employer dashboard, paste, post. Once you’re an approved Indeed Apply partner we can wire applicant ingest into this page.
      </p>
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function AddJobForm({ onAdd, onCancel }: { onAdd: (j: Omit<JobOpening, "id" | "createdAt">) => void; onCancel: () => void }) {
  const [form, setForm] = useState<Omit<JobOpening, "id" | "createdAt">>(() => ({
    organizationSlug: ALL_ORGANIZATIONS[0]?.slug ?? "south-armz-global",
    title: "",
    employmentType: "Full-time",
    status: "Draft",
    location: "Pittsboro, NC",
  }));

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title.trim()) return;
    onAdd(form);
  }

  return (
    <Card>
      <CardContent className="p-6">
        <form onSubmit={submit} className="grid gap-3 md:grid-cols-2">
          <Field label="Hiring entity">
            <select
              value={form.organizationSlug}
              onChange={(e) => setForm({ ...form, organizationSlug: e.target.value })}
              className="mt-1 w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {ALL_ORGANIZATIONS.map((o) => (
                <option key={o.slug} value={o.slug}>{o.emoji} {o.name}</option>
              ))}
            </select>
          </Field>
          <Field label="Job title">
            <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="e.g. Head Brewer, Bartender, Tour Guide" required />
          </Field>
          <Field label="Employment type">
            <select
              value={form.employmentType}
              onChange={(e) => setForm({ ...form, employmentType: e.target.value as EmploymentType })}
              className="mt-1 w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option>Full-time</option>
              <option>Part-time</option>
              <option>Contract</option>
              <option>Internship</option>
              <option>Temporary</option>
            </select>
          </Field>
          <Field label="Location">
            <Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} placeholder="Pittsboro, NC" />
          </Field>
          <Field label="Comp type">
            <select
              value={form.compType ?? ""}
              onChange={(e) => setForm({ ...form, compType: (e.target.value || undefined) as "salary" | "hourly" | undefined })}
              className="mt-1 w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="">— Choose —</option>
              <option value="salary">Salary (annual)</option>
              <option value="hourly">Hourly</option>
            </select>
          </Field>
          <Field label="Comp range (min / max)">
            <div className="mt-1 flex gap-2">
              <Input type="number" placeholder="min" value={form.compMin ?? ""} onChange={(e) => setForm({ ...form, compMin: parseFloat(e.target.value) || undefined })} />
              <Input type="number" placeholder="max" value={form.compMax ?? ""} onChange={(e) => setForm({ ...form, compMax: parseFloat(e.target.value) || undefined })} />
            </div>
          </Field>
          <div className="md:col-span-2 flex justify-end gap-2 mt-2">
            <Button type="button" variant="ghost" size="sm" onClick={onCancel}>Cancel</Button>
            <Button type="submit" variant="brand" size="sm">Open role</Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

function Field({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {
  return (
    <div className={className}>
      <span className="text-xs text-muted-foreground">{label}</span>
      {children}
    </div>
  );
}

