"use client";

import { useState } from "react";
import { Modal } from "@/components/ui/modal";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import type { MeetingTemplate, TeamMember } from "@/types";

const TEMPLATE_COLORS = [
  { label: "Default", value: "#6366f1" },
  { label: "Red", value: "#ef4444" },
  { label: "Orange", value: "#f97316" },
  { label: "Green", value: "#22c55e" },
  { label: "Blue", value: "#3b82f6" },
  { label: "Purple", value: "#8b5cf6" },
  { label: "Pink", value: "#ec4899" },
];

export interface MeetingTemplateFormData {
  name: string;
  description: string;
  duration_minutes: number;
  all_day: boolean;
  color: string | null;
  participant_ids: string[];
}

interface MeetingTemplateFormProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: MeetingTemplateFormData) => Promise<void>;
  template?: MeetingTemplate | null;
  members?: TeamMember[];
}

export function MeetingTemplateForm({
  open,
  onClose,
  onSubmit,
  template,
  members = [],
}: MeetingTemplateFormProps) {
  const isEditing = !!template;
  const [name, setName] = useState(template?.name || "");
  const [description, setDescription] = useState(template?.description || "");
  const [durationMinutes, setDurationMinutes] = useState(String(template?.duration_minutes || 60));
  const [allDay, setAllDay] = useState(template?.all_day || false);
  const [color, setColor] = useState(template?.color || TEMPLATE_COLORS[0].value);
  const [participantIds, setParticipantIds] = useState<string[]>(
    template?.participants?.map((participant) => participant.id) || []
  );
  const [submitting, setSubmitting] = useState(false);

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!name.trim() || submitting) return;

    setSubmitting(true);
    await onSubmit({
      name: name.trim(),
      description: description.trim(),
      duration_minutes: Math.max(15, Number.parseInt(durationMinutes, 10) || 60),
      all_day: allDay,
      color,
      participant_ids: participantIds,
    });
    setSubmitting(false);
    onClose();
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? "Edit meeting template" : "New meeting template"}
      className="max-w-lg"
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-1.5">
          <Label>Template name</Label>
          <Input
            value={name}
            onChange={(event) => setName(event.target.value)}
            placeholder="Weekly leadership sync"
            autoFocus
            required
          />
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-muted-foreground">Agenda / description</Label>
          <Textarea
            value={description}
            onChange={(event) => setDescription(event.target.value)}
            placeholder="Topics, expected outcome, or recurring agenda..."
            className="min-h-[100px]"
          />
        </div>

        <div className="grid gap-3 sm:grid-cols-2">
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Duration (minutes)</Label>
            <Input
              type="text"
              inputMode="numeric"
              value={durationMinutes}
              onChange={(event) => {
                const raw = event.target.value;
                if (!/^[0-9]*$/.test(raw)) return;
                setDurationMinutes(raw);
              }}
              onBlur={() =>
                setDurationMinutes(String(Math.max(15, Number.parseInt(durationMinutes, 10) || 60)))
              }
              disabled={allDay}
            />
          </div>
          <label className="flex items-center gap-2 pt-6">
            <input
              type="checkbox"
              checked={allDay}
              onChange={(event) => setAllDay(event.target.checked)}
              className="rounded border-input"
            />
            <span className="text-sm">All day meeting</span>
          </label>
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-muted-foreground">Color</Label>
          <div className="flex gap-1.5">
            {TEMPLATE_COLORS.map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => setColor(option.value)}
                className={cn(
                  "h-6 w-6 rounded-full cursor-pointer transition-transform",
                  color === option.value && "scale-110 ring-2 ring-ring ring-offset-2"
                )}
                style={{ backgroundColor: option.value }}
                title={option.label}
              />
            ))}
          </div>
        </div>

        {members.length > 0 && (
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">Default participants</Label>
            <div className="flex flex-wrap gap-2">
              {members.map((member) => {
                const selected = participantIds.includes(member.user_id);
                const label =
                  member.profile?.full_name || member.profile?.email || "Team member";

                return (
                  <button
                    key={member.user_id}
                    type="button"
                    onClick={() =>
                      setParticipantIds((prev) =>
                        prev.includes(member.user_id)
                          ? prev.filter((id) => id !== member.user_id)
                          : [...prev, member.user_id]
                      )
                    }
                    className={cn(
                      "rounded-full border px-2.5 py-1 text-xs transition-colors",
                      selected
                        ? "border-primary bg-primary/10 text-primary"
                        : "border-border bg-background text-muted-foreground hover:text-foreground"
                    )}
                  >
                    {label}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div className="flex justify-end gap-2 pt-2">
          <Button type="button" variant="ghost" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit" disabled={!name.trim() || submitting}>
            {submitting
              ? isEditing
                ? "Saving..."
                : "Creating..."
              : isEditing
              ? "Save template"
              : "Create template"}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
