"use client"
import React, { useState } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useCreateSupportTicket, useGetSupportTickets } from "@/lib/react-query/hooks/support"
import { useAuth } from "@/context/AuthContext"
import type { CreateSupportTicketPayload, SupportTicket } from "@/types/support"
import { MessageSquare, AlertCircle, Clock, Zap, Badge, Plus } from "lucide-react"
import { CustomTabs, TabsContent } from "@/components/common/CustomTabs"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { format } from "date-fns"
import { useTranslations } from "next-intl"

const errorInputClass = "h-12 border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200 px-2 py-4 text-base"
const normalInputClass = "h-12 border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20 px-2 py-4 text-base"

const supportTicketSchema = z.object({
  subject: z.string().min(5, "Subject must be at least 5 characters"),
  description: z.string().min(20, "Description must be at least 20 characters"),
  priority: z.enum(["low", "medium", "high", "urgent"])
})

type SupportFormValues = z.infer<typeof supportTicketSchema>

export default function SupportMain() {
  const t = useTranslations("support")

  const { user } = useAuth()
  const createSupportTicketMutation = useCreateSupportTicket()
  const { data: tickets, isLoading: ticketsLoading } = useGetSupportTickets(user?.id || "")
  const [activeTab, setActiveTab] = useState("submit")

  const supportTicketSchema = z.object({
    subject: z.string().min(5, t("form.subject.validation.minLength")),
    description: z.string().min(20, t("form.description.validation.minLength")),
    priority: z.enum(["low", "medium", "high", "urgent"])
  })

  const form = useForm<SupportFormValues>({
    resolver: zodResolver(supportTicketSchema),
    defaultValues: {
      subject: "",
      description: "",
      priority: "medium"
    }
  })

  const onSubmit = async (values: SupportFormValues) => {
    if (!user?.id) {
      console.error("User not authenticated")
      return
    }

    const payload: CreateSupportTicketPayload = {
      ...values,
      source: "salon",
      requesterId: user.id
    }

    await createSupportTicketMutation.mutateAsync(payload)
    form.reset()
  }

  const priorityOptions = [
    {
      value: "low",
      label: t("form.priority.options.low.label"),
      icon: Clock,
      description: t("form.priority.options.low.description"),
      color: "text-green-600"
    },
    {
      value: "medium",
      label: t("form.priority.options.medium.label"),
      icon: MessageSquare,
      description: t("form.priority.options.medium.description"),
      color: "text-yellow-600"
    },
    {
      value: "high",
      label: t("form.priority.options.high.label"),
      icon: AlertCircle,
      description: t("form.priority.options.high.description"),
      color: "text-orange-600"
    },
    {
      value: "urgent",
      label: t("form.priority.options.urgent.label"),
      icon: Zap,
      description: t("form.priority.options.urgent.description"),
      color: "text-red-600"
    }
  ]

  const getPriorityColor = (priority: string) => {
    const option = priorityOptions.find(opt => opt.value === priority)
    return option?.color || "text-gray-600"
  }

  const getPriorityIcon = (priority: string) => {
    const option = priorityOptions.find(opt => opt.value === priority)
    return option?.icon || MessageSquare
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case "open":
        return "bg-blue-100 text-blue-800"
      case "in-progress":
        return "bg-yellow-100 text-yellow-800"
      case "resolved":
        return "bg-green-100 text-green-800"
      case "closed":
        return "bg-gray-100 text-gray-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  const formatDate = (dateString: string) => {
    try {
      return format(new Date(dateString), "MMM dd, yyyy 'at' HH:mm")
    } catch {
      return dateString
    }
  }

  const tabItems = [
    {
      value: "submit",
      label: t("tabs.submit")
    },
    {
      value: "tickets",
      label: t("tabs.tickets"),
      count: tickets?.length || 0
    }
  ]

  return (
    <div className="w-full space-y-6">
      {/* <div className="text-center space-y-2">
        <h2 className="text-2xl font-bold text-gray-900">{t("header.title")}</h2>
        <p className="text-gray-600">
          {t("header.description")}
        </p>
      </div> */}

      <CustomTabs
        items={tabItems}
        activeValue={activeTab}
        onTabChange={setActiveTab}
        className="w-full"
      >
        <TabsContent value="submit" className="space-y-6">
          <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                {/* Subject Field */}
                <FormField
                  name="subject"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormItem>
                      <FormLabel className="text-sm font-medium text-gray-700">
                        {t("form.subject.label")} <span className="text-red-500">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          className={fieldState.invalid ? errorInputClass : normalInputClass}
                          placeholder={t("form.subject.placeholder")}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Description Field */}
                <FormField
                  name="description"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormItem>
                      <FormLabel className="text-sm font-medium text-gray-700">
                        {t("form.description.label")} <span className="text-red-500">*</span>
                      </FormLabel>
                      <FormControl>
                        <Textarea
                          className={`min-h-[120px] resize-none ${
                            fieldState.invalid
                              ? "border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200"
                              : "border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20"
                          } px-3 py-3 text-base`}
                          placeholder={t("form.description.placeholder")}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Priority Field */}
                <FormField
                  name="priority"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm font-medium text-gray-700">
                        {t("form.priority.label")} <span className="text-red-500">*</span>
                      </FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger className="h-12 border-gray-300 focus:border-primary-blue focus:ring-2 focus:ring-primary-blue/20">
                            <SelectValue placeholder={t("form.priority.placeholder")} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {priorityOptions.map((option) => {
                            const Icon = option.icon
                            return (
                              <SelectItem key={option.value} value={option.value}>
                                <div className="flex items-center gap-3">
                                  <Icon className={`w-4 h-4 ${option.color}`} />
                                  <div>
                                    <div className="font-medium">{option.label}</div>
                                    <div className="text-xs text-gray-500">{option.description}</div>
                                  </div>
                                </div>
                              </SelectItem>
                            )
                          })}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Submit Button */}
                <div className="flex justify-end pt-4">
                  <Button
                    type="submit"
                    className="bg-primary-gradient text-white px-8 py-3 h-12"
                    disabled={createSupportTicketMutation.isPending}
                  >
                    {createSupportTicketMutation.isPending ? (
                      <div className="flex items-center gap-2">
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        {t("form.submit.submitting")}
                      </div>
                    ) : (
                      t("form.submit.submit")
                    )}
                  </Button>
                </div>
              </form>
            </Form>
          </div>
        </TabsContent>

        <TabsContent value="tickets" className="space-y-4">
          {ticketsLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="w-8 h-8 border-4 border-primary-blue border-t-transparent rounded-full animate-spin" />
            </div>
          ) : tickets && tickets.length > 0 ? (
            <div className="space-y-4">
              {tickets.map((ticket) => {
                const PriorityIcon = getPriorityIcon(ticket.priority)
                return (
                  <Card key={ticket._id} className="hover:shadow-md transition-shadow">
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <CardTitle className="text-lg font-semibold text-gray-900 mb-2">
                            {ticket.subject}
                          </CardTitle>
                          <div className="flex items-center gap-4 text-sm text-gray-600">
                            <div className="flex items-center gap-1">
                              <PriorityIcon className={`w-4 h-4 ${getPriorityColor(ticket.priority)}`} />
                              <span className="capitalize">{ticket.priority}</span>
                            </div>
                            <span>•</span>
                            <span>{formatDate(ticket.createdAt || "")}</span>
                          </div>
                        </div>
                        <Badge className={`capitalize ${getStatusColor(ticket.status || "open")}`}>
                          {t(`tickets.status.${ticket.status || "open"}`)}
                        </Badge>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <p className="text-gray-700 leading-relaxed">
                        {ticket.description.length > 200
                          ? `${ticket.description.substring(0, 200)}...`
                          : ticket.description
                        }
                      </p>
                    </CardContent>
                  </Card>
                )
              })}
            </div>
          ) : (
            <div className="text-center py-12">
              <MessageSquare className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">{t("tickets.empty.title")}</h3>
              <p className="text-gray-600 mb-4">
                {t("tickets.empty.description")}
              </p>
              <Button
                onClick={() => setActiveTab("submit")}
                className="bg-primary-gradient text-white"
              >
                <Plus className="w-4 h-4 mr-2" />
                {t("tickets.empty.action")}
              </Button>
            </div>
          )}
        </TabsContent>
      </CustomTabs>      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <MessageSquare className="w-5 h-5 text-blue-600 mt-0.5" />
          <div className="text-sm text-blue-800">
            <p className="font-medium mb-1">{t("help.title")}</p>
            <p>
              {t("help.description")}
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
