"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { LEAD_STATUSES } from "@/lib/leads/constants";
import type { MasterRow } from "@/lib/types";
import {
  addNote,
  addFollowup,
  completeFollowup,
  changeStatus,
  assignUsers,
} from "./actions";

const textareaClass =
  "flex min-h-20 w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50";

/* -------------------------------------------------------------------------- */
/* Status changer                                                             */
/* -------------------------------------------------------------------------- */

export function StatusChanger({
  leadId,
  current,
}: {
  leadId: string;
  current: string;
}) {
  const [value, setValue] = useState(current);
  const [pending, startTransition] = useTransition();

  function onChange(next: string) {
    const prev = value;
    setValue(next);
    startTransition(async () => {
      const res = await changeStatus(leadId, next);
      if (res.error) {
        setValue(prev);
        toast.error(res.error);
      } else {
        toast.success(`Status set to ${next}`);
      }
    });
  }

  return (
    <Select value={value} onValueChange={onChange} disabled={pending}>
      <SelectTrigger className="w-44">
        <SelectValue placeholder="Status" />
      </SelectTrigger>
      <SelectContent>
        {LEAD_STATUSES.map((s) => (
          <SelectItem key={s} value={s}>
            {s}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

/* -------------------------------------------------------------------------- */
/* Add note                                                                   */
/* -------------------------------------------------------------------------- */

export function AddNoteForm({ leadId }: { leadId: string }) {
  const [body, setBody] = useState("");
  const [pending, startTransition] = useTransition();

  function submit() {
    if (!body.trim()) {
      toast.error("Note cannot be empty");
      return;
    }
    startTransition(async () => {
      const res = await addNote(leadId, body);
      if (res.error) {
        toast.error(res.error);
      } else {
        setBody("");
        toast.success("Note added");
      }
    });
  }

  return (
    <div className="space-y-2">
      <Label htmlFor="note-body">New note</Label>
      <textarea
        id="note-body"
        className={textareaClass}
        placeholder="Write a note about this lead…"
        value={body}
        onChange={(e) => setBody(e.target.value)}
      />
      <Button onClick={submit} disabled={pending} size="sm">
        {pending ? "Adding…" : "Add note"}
      </Button>
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* Add follow-up                                                              */
/* -------------------------------------------------------------------------- */

export function AddFollowupForm({
  leadId,
  followupTypes,
}: {
  leadId: string;
  followupTypes: MasterRow[];
}) {
  const [nextDate, setNextDate] = useState("");
  const [fromTime, setFromTime] = useState("");
  const [toTime, setToTime] = useState("");
  const [typeId, setTypeId] = useState<string>("");
  const [notes, setNotes] = useState("");
  const [pending, startTransition] = useTransition();

  function submit() {
    if (!nextDate) {
      toast.error("Pick a follow-up date");
      return;
    }
    startTransition(async () => {
      const res = await addFollowup(leadId, {
        next_date: nextDate,
        from_time: fromTime || undefined,
        to_time: toTime || undefined,
        followup_type_id: typeId || undefined,
        notes: notes || undefined,
      });
      if (res.error) {
        toast.error(res.error);
      } else {
        setNextDate("");
        setFromTime("");
        setToTime("");
        setTypeId("");
        setNotes("");
        toast.success("Follow-up scheduled");
      }
    });
  }

  return (
    <div className="space-y-3 rounded-lg border p-4">
      <p className="text-sm font-medium">Schedule a follow-up</p>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
        <div className="space-y-1.5">
          <Label htmlFor="fu-date">Date</Label>
          <Input
            id="fu-date"
            type="date"
            value={nextDate}
            onChange={(e) => setNextDate(e.target.value)}
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="fu-from">From</Label>
          <Input
            id="fu-from"
            type="time"
            value={fromTime}
            onChange={(e) => setFromTime(e.target.value)}
          />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="fu-to">To</Label>
          <Input
            id="fu-to"
            type="time"
            value={toTime}
            onChange={(e) => setToTime(e.target.value)}
          />
        </div>
      </div>
      <div className="space-y-1.5">
        <Label>Type</Label>
        <Select value={typeId} onValueChange={setTypeId}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select a type" />
          </SelectTrigger>
          <SelectContent>
            {followupTypes.map((t) => (
              <SelectItem key={t.id} value={t.id}>
                {t.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-1.5">
        <Label htmlFor="fu-notes">Notes</Label>
        <textarea
          id="fu-notes"
          className={textareaClass}
          placeholder="Optional notes…"
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
        />
      </div>
      <Button onClick={submit} disabled={pending} size="sm">
        {pending ? "Scheduling…" : "Schedule follow-up"}
      </Button>
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* Complete follow-up                                                         */
/* -------------------------------------------------------------------------- */

export function CompleteFollowupButton({
  followupId,
  leadId,
}: {
  followupId: string;
  leadId: string;
}) {
  const [open, setOpen] = useState(false);
  const [outcome, setOutcome] = useState("");
  const [pending, startTransition] = useTransition();

  function submit() {
    startTransition(async () => {
      const res = await completeFollowup(followupId, leadId, outcome);
      if (res.error) {
        toast.error(res.error);
      } else {
        setOpen(false);
        setOutcome("");
        toast.success("Follow-up marked done");
      }
    });
  }

  if (!open) {
    return (
      <Button size="sm" variant="outline" onClick={() => setOpen(true)}>
        Mark done
      </Button>
    );
  }

  return (
    <div className="mt-2 space-y-2">
      <textarea
        className={textareaClass}
        placeholder="Outcome (optional)…"
        value={outcome}
        onChange={(e) => setOutcome(e.target.value)}
      />
      <div className="flex gap-2">
        <Button size="sm" onClick={submit} disabled={pending}>
          {pending ? "Saving…" : "Confirm done"}
        </Button>
        <Button
          size="sm"
          variant="ghost"
          onClick={() => setOpen(false)}
          disabled={pending}
        >
          Cancel
        </Button>
      </div>
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* Assignment editor                                                          */
/* -------------------------------------------------------------------------- */

export function AssignmentEditor({
  leadId,
  assignableUsers,
  currentUserIds,
}: {
  leadId: string;
  assignableUsers: { id: string; full_name: string }[];
  currentUserIds: string[];
}) {
  const [selected, setSelected] = useState<Set<string>>(
    new Set(currentUserIds),
  );
  const [pending, startTransition] = useTransition();

  function toggle(id: string, checked: boolean) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (checked) next.add(id);
      else next.delete(id);
      return next;
    });
  }

  function save() {
    startTransition(async () => {
      const res = await assignUsers(leadId, [...selected]);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success("Assignments updated");
      }
    });
  }

  return (
    <div className="space-y-3">
      <div className="space-y-2">
        {assignableUsers.length === 0 && (
          <p className="text-sm text-muted-foreground">
            No assignable users available.
          </p>
        )}
        {assignableUsers.map((u) => {
          const checked = selected.has(u.id);
          return (
            <label
              key={u.id}
              className="flex cursor-pointer items-center gap-2.5 text-sm"
            >
              <Checkbox
                checked={checked}
                onCheckedChange={(c) => toggle(u.id, c === true)}
              />
              <span>{u.full_name}</span>
            </label>
          );
        })}
      </div>
      <Button onClick={save} disabled={pending} size="sm">
        {pending ? "Saving…" : "Save assignments"}
      </Button>
    </div>
  );
}
