"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
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 { ReactSelect } from "@/components/ui/react-select"
import { Plus, FileText } from "lucide-react"
import type { ActivityType } from "./types"
import type { CreateActivityInput } from "@/api/rtk/activities-api"

interface LogActivityModalProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (data: CreateActivityInput) => Promise<void>
  isSubmitting?: boolean
}

const ACTIVITY_TYPES: { type: ActivityType; label: string }[] = [
  { type: "Call", label: "Call" },
  { type: "Email", label: "Email" },
  { type: "Meeting", label: "Meeting" },
  { type: "Note", label: "Note" },
  { type: "Deal", label: "Deal" },
  { type: "Win", label: "Win" },
]

const TEAMS = [
  { value: "alpha", label: "Team Alpha" },
  { value: "beta", label: "Team Beta" },
  { value: "gamma", label: "Team Gamma" },
]

export function LogActivityModal({
  isOpen,
  onClose,
  onSubmit,
  isSubmitting = false,
}: LogActivityModalProps) {
  const [formData, setFormData] = React.useState({
    type: "Note" as ActivityType,
    subject: "",
    company: "",
    duration: "",
    team: "alpha",
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!formData.subject.trim()) return
    try {
      await onSubmit({
        type: formData.type,
        subject: formData.subject.trim(),
        company: formData.company.trim() || undefined,
        duration: formData.duration ? parseInt(formData.duration, 10) : undefined,
        team: formData.team,
      })
      setFormData({
        type: "Note",
        subject: "",
        company: "",
        duration: "",
        team: "alpha",
      })
      onClose()
    } catch {
      // Error handling in parent (toast)
    }
  }

  const handleOpenChange = (open: boolean) => {
    if (!open) onClose()
  }

  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[520px] p-0 overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="bg-accent/5 px-8 pt-8 pb-6 border-b border-accent/10">
          <DialogHeader>
            <DialogTitle className="text-[24px] font-extrabold font-['Lexend'] text-text tracking-tight flex items-center gap-3">
              <div className="size-10 rounded-2xl bg-accent flex items-center justify-center text-white">
                <Plus size={22} strokeWidth={3} />
              </div>
              Log Activity
            </DialogTitle>
            <DialogDescription className="text-[13px] font-['Lexend_Deca'] text-gray-500 mt-1 ml-13">
              Record a call, email, meeting, note, or deal update.
            </DialogDescription>
          </DialogHeader>
        </div>

        <form onSubmit={handleSubmit} className="p-8 pt-6 space-y-5">
          <div className="space-y-2">
            <Label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] ml-1">
              Activity Type
            </Label>
            <ReactSelect
              value={formData.type}
              onValueChange={(val) =>
                setFormData({ ...formData, type: val as ActivityType })
              }
              options={ACTIVITY_TYPES.map((t) => ({
                value: t.type,
                label: t.label,
              }))}
              aria-label="Activity type"
              triggerClassName="h-11 rounded-xl border-border/60 font-['Lexend'] text-[14px] bg-bg/10"
              contentClassName="rounded-xl"
            />
          </div>

          <div className="space-y-2">
            <Label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] ml-1 flex items-center gap-1.5">
              <FileText size={12} className="text-accent" /> Subject / Description
            </Label>
            <Textarea
              placeholder="e.g. Discovery call — 25 mins, Proposal sent via email..."
              className="min-h-[80px] rounded-xl border-border/60 font-['Lexend'] text-[14px] px-4 py-3 bg-bg/10 resize-none"
              value={formData.subject}
              onChange={(e) =>
                setFormData({ ...formData, subject: e.target.value })}
              required
            />
          </div>

          <div className="space-y-2">
            <Label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] ml-1">
              Company (optional)
            </Label>
            <Input
              placeholder="Company name..."
              className="h-11 rounded-xl border-border/60 font-['Lexend'] text-[14px] px-4 bg-bg/10"
              value={formData.company}
              onChange={(e) =>
                setFormData({ ...formData, company: e.target.value })}
            />
          </div>

          {formData.type === "Call" && (
            <div className="space-y-2">
              <Label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] ml-1">
                Duration (minutes)
              </Label>
              <Input
                type="number"
                min={1}
                placeholder="e.g. 30"
                className="h-11 rounded-xl border-border/60 font-['Lexend'] text-[14px] px-4 bg-bg/10"
                value={formData.duration}
                onChange={(e) =>
                  setFormData({ ...formData, duration: e.target.value })}
              />
            </div>
          )}

          <div className="space-y-2">
            <Label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca'] ml-1">
              Team
            </Label>
            <ReactSelect
              value={formData.team}
              onValueChange={(val) => setFormData({ ...formData, team: val })}
              options={TEAMS.map((t) => ({
                value: t.value,
                label: t.label,
              }))}
              aria-label="Team"
              triggerClassName="h-11 rounded-xl border-border/60 font-['Lexend'] text-[14px] bg-bg/10"
              contentClassName="rounded-xl"
            />
          </div>

          <DialogFooter className="pt-4 gap-3 flex-row sm:justify-end">
            <Button
              type="button"
              variant="ghost"
              onClick={onClose}
              className="rounded-xl font-bold h-11 px-6 text-gray-500 hover:bg-white"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isSubmitting || !formData.subject.trim()}
              className="rounded-xl bg-accent px-10 font-extrabold text-white h-11 shadow-premium hover:shadow-lg hover:scale-[1.01] transition-all duration-200"
            >
              {isSubmitting ? "Saving..." : "Log Activity"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
