"use client"

import { useState, useEffect } from "react"
import { getJobsByPlumberId, type PlumberJob } from "@/lib/plumber-jobs"
import JobCard from "@/components/plumber/job-card"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Briefcase, Filter } from "lucide-react"

export default function PlumberJobsPage() {
  const [jobs, setJobs] = useState<PlumberJob[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // محاكاة جلب البيانات
    const fetchJobs = async () => {
      try {
        const plumberJobs = getJobsByPlumberId("1") // معرف السباك الحالي
        setJobs(plumberJobs)
      } catch (error) {
        console.error("Error fetching jobs:", error)
      } finally {
        setLoading(false)
      }
    }

    fetchJobs()
  }, [])

  const handleAcceptJob = async (jobId: string) => {
    try {
      // هنا سيتم إرسال طلب لقبول المهمة
      console.log("Accepting job:", jobId)

      setJobs((prev) => prev.map((job) => (job.id === jobId ? { ...job, status: "accepted" as const } : job)))
    } catch (error) {
      console.error("Error accepting job:", error)
    }
  }

  const handleRejectJob = async (jobId: string) => {
    try {
      // هنا سيتم إرسال طلب لرفض المهمة
      console.log("Rejecting job:", jobId)

      setJobs((prev) => prev.map((job) => (job.id === jobId ? { ...job, status: "cancelled" as const } : job)))
    } catch (error) {
      console.error("Error rejecting job:", error)
    }
  }

  const handleStartJob = async (jobId: string) => {
    try {
      console.log("Starting job:", jobId)

      setJobs((prev) =>
        prev.map((job) =>
          job.id === jobId
            ? {
                ...job,
                status: "in-progress" as const,
                startTime: new Date().toISOString(),
              }
            : job,
        ),
      )
    } catch (error) {
      console.error("Error starting job:", error)
    }
  }

  const handleCompleteJob = async (jobId: string) => {
    try {
      console.log("Completing job:", jobId)

      setJobs((prev) =>
        prev.map((job) =>
          job.id === jobId
            ? {
                ...job,
                status: "completed" as const,
                endTime: new Date().toISOString(),
                completedAt: new Date().toISOString(),
              }
            : job,
        ),
      )
    } catch (error) {
      console.error("Error completing job:", error)
    }
  }

  const pendingJobs = jobs.filter((job) => job.status === "pending")
  const acceptedJobs = jobs.filter((job) => job.status === "accepted")
  const inProgressJobs = jobs.filter((job) => job.status === "in-progress")
  const completedJobs = jobs.filter((job) => job.status === "completed")

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[var(--parg-color)]">جاري التحميل...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-[var(--dark-color)]">إدارة المهام</h1>
          <p className="text-[var(--parg-color)]">تتبع وإدارة جميع مهامك</p>
        </div>
        <Button variant="outline">
          <Filter className="w-4 h-4 ml-2" />
          تصفية
        </Button>
      </div>

      <Tabs defaultValue="pending" className="space-y-6">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="pending" className="relative">
            في الانتظار
            {pendingJobs.length > 0 && (
              <span className="absolute -top-1 -right-1 bg-[var(--main-color)] text-[var(--dark-color)] text-xs rounded-full w-5 h-5 flex items-center justify-center">
                {pendingJobs.length}
              </span>
            )}
          </TabsTrigger>
          <TabsTrigger value="accepted">مقبولة ({acceptedJobs.length})</TabsTrigger>
          <TabsTrigger value="in-progress">قيد التنفيذ ({inProgressJobs.length})</TabsTrigger>
          <TabsTrigger value="completed">مكتملة ({completedJobs.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="pending">
          {pendingJobs.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {pendingJobs.map((job) => (
                <JobCard key={job.id} job={job} onAccept={handleAcceptJob} onReject={handleRejectJob} />
              ))}
            </div>
          ) : (
            <Card className="border-[var(--border-color)]">
              <CardContent className="text-center py-16">
                <Briefcase className="w-16 h-16 mx-auto text-[var(--parg-color)] mb-4" />
                <h3 className="text-xl font-semibold text-[var(--dark-color)] mb-2">لا توجد مهام معلقة</h3>
                <p className="text-[var(--parg-color)]">ستظهر المهام الجديدة هنا عند توفرها</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="accepted">
          {acceptedJobs.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {acceptedJobs.map((job) => (
                <JobCard key={job.id} job={job} onStart={handleStartJob} />
              ))}
            </div>
          ) : (
            <Card className="border-[var(--border-color)]">
              <CardContent className="text-center py-16">
                <Briefcase className="w-16 h-16 mx-auto text-[var(--parg-color)] mb-4" />
                <h3 className="text-xl font-semibold text-[var(--dark-color)] mb-2">لا توجد مهام مقبولة</h3>
                <p className="text-[var(--parg-color)]">المهام التي تقبلها ستظهر هنا</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="in-progress">
          {inProgressJobs.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {inProgressJobs.map((job) => (
                <JobCard key={job.id} job={job} onComplete={handleCompleteJob} />
              ))}
            </div>
          ) : (
            <Card className="border-[var(--border-color)]">
              <CardContent className="text-center py-16">
                <Briefcase className="w-16 h-16 mx-auto text-[var(--parg-color)] mb-4" />
                <h3 className="text-xl font-semibold text-[var(--dark-color)] mb-2">لا توجد مهام قيد التنفيذ</h3>
                <p className="text-[var(--parg-color)]">المهام التي تعمل عليها حالياً ستظهر هنا</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="completed">
          {completedJobs.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {completedJobs.map((job) => (
                <JobCard key={job.id} job={job} />
              ))}
            </div>
          ) : (
            <Card className="border-[var(--border-color)]">
              <CardContent className="text-center py-16">
                <Briefcase className="w-16 h-16 mx-auto text-[var(--parg-color)] mb-4" />
                <h3 className="text-xl font-semibold text-[var(--dark-color)] mb-2">لا توجد مهام مكتملة</h3>
                <p className="text-[var(--parg-color)]">المهام المكتملة ستظهر هنا مع تقييمات العملاء</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}
