"use client";

import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { 
  CheckCircle2, 
  Clock, 
  MessageSquare, 
  Send, 
  FolderKanban, 
  ShieldCheck, 
  FileText, 
  Terminal, 
  UserCheck, 
  Phone, 
  Mail, 
  ExternalLink,
  ChevronRight,
  Sparkles,
  Paperclip,
  Check,
  LogOut,
  Lock
} from "lucide-react";
import { useAppStore } from "@/lib/store";
import { Project, ChatMessage } from "@/types";
import { ThemeToggle } from "@/components/ui/ThemeToggle";

export default function ClientPortalPage() {
  const router = useRouter();
  const { 
    currentUser, 
    logout, 
    projects, 
    tasks, 
    chatMessages, 
    sendChatMessage,
    isLoaded
  } = useAppStore();

  const [activeTab, setActiveTab] = useState<"status" | "chat" | "invoices">("status");
  const [chatInput, setChatInput] = useState("");

  if (isLoaded && !currentUser) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4 bg-background text-foreground">
        <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center space-y-4 shadow-xl">
          <div className="relative h-12 w-12 mx-auto overflow-hidden rounded-xl bg-card border border-[#024d37]/40 p-1 flex items-center justify-center">
            <Image src="/assets/logo/logo.png" alt="AetherSoft" width={40} height={40} className="object-contain" />
          </div>
          <h2 className="text-xl font-bold">Authentication Required</h2>
          <p className="text-xs text-muted-foreground">
            Please sign in with your client account to access your live project dashboard and architect chat.
          </p>
          <div className="flex gap-2 pt-2">
            <Link
              href="/login"
              className="flex-1 rounded-full bg-[#024d37] py-2.5 font-mono text-xs font-bold text-white text-center hover:bg-[#036549]"
            >
              Sign In →
            </Link>
            <Link
              href="/register"
              className="flex-1 rounded-full border border-border bg-muted py-2.5 font-mono text-xs text-foreground text-center"
            >
              Register Account
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const clientProjects = projects.filter(
    (p) => p.client_id === currentUser?.id || p.client_email?.toLowerCase() === currentUser?.email.toLowerCase()
  );
  const activeProject = clientProjects[0] || projects[0];
  const projectTasks = tasks.filter((t) => t.project_id === activeProject?.id);
  const relevantChat = chatMessages.filter(
    (m) => m.client_id === currentUser?.id || m.project_id === activeProject?.id
  );

  const handleSendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (!chatInput.trim() || !currentUser) return;
    sendChatMessage(chatInput, currentUser.id, activeProject?.id);
    setChatInput("");
  };

  const handleQuickPrompt = (promptText: string) => {
    if (!currentUser) return;
    sendChatMessage(promptText, currentUser.id, activeProject?.id);
  };

  const handleLogout = () => {
    logout();
    router.push("/");
  };

  return (
    <div className="min-h-screen bg-background text-foreground flex flex-col">
      {/* Top Client Header */}
      <header className="sticky top-0 z-40 border-b border-border bg-card/80 backdrop-blur-md px-4 sm:px-8 py-3">
        <div className="mx-auto max-w-7xl flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Link href="/" aria-label="Home" className="flex items-center gap-2 transition-transform hover:scale-105">
              <div className="relative h-9 w-9 overflow-hidden rounded-xl bg-card border border-[#024d37]/40 p-1 flex items-center justify-center shadow-sm shadow-[#024d37]/15">
                <Image
                  src="/assets/logo/logo.png"
                  alt="AetherSoft Logo"
                  width={30}
                  height={30}
                  className="object-contain"
                />
              </div>
            </Link>
            <div>
              <div className="flex items-center gap-2">
                <span className="font-bold text-sm text-foreground">Client Command Hub</span>
                <span className="rounded-full bg-[#024d37]/15 border border-[#024d37]/40 px-2 py-0.2 font-mono text-[9px] text-[#024d37] font-semibold">
                  LIVE SLA
                </span>
              </div>
              <p className="text-[11px] font-mono text-muted-foreground">
                Client: <strong className="text-foreground">{currentUser?.name}</strong> ({currentUser?.company || "Organization"})
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <ThemeToggle />

            <button
              onClick={handleLogout}
              className="flex items-center gap-1.5 rounded-full border border-border bg-muted px-3.5 py-1.5 font-mono text-xs text-muted-foreground hover:text-destructive hover:border-destructive/40 transition-colors"
            >
              <LogOut className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">Sign Out</span>
            </button>
          </div>
        </div>
      </header>

      {/* Main Container */}
      <main className="flex-1 mx-auto max-w-7xl w-full p-4 sm:p-6 lg:p-8 space-y-6">
        {/* Project Selector & Status Banner */}
        <div className="rounded-2xl border border-border bg-card p-6 sm:p-8 flex flex-col md:flex-row md:items-center justify-between gap-6 shadow-sm">
          <div className="space-y-2">
            <div className="flex flex-wrap items-center gap-2 font-mono text-xs">
              <span className="flex h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
              <span className="text-[#024d37] font-semibold">// ACTIVE PROJECT ENGAGEMENT</span>
              <span className="text-border">|</span>
              <span className="text-muted-foreground">ID: {activeProject?.id.toUpperCase()}</span>
            </div>

            <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-foreground">
              {activeProject?.name}
            </h1>

            <p className="text-xs text-muted-foreground max-w-2xl leading-relaxed">
              {activeProject?.description}
            </p>
          </div>

          <div className="flex flex-col sm:flex-row md:flex-col gap-3 min-w-[240px]">
            <div className="rounded-xl border border-border bg-muted p-4 space-y-1 font-mono text-xs">
              <div className="flex justify-between text-muted-foreground text-[10px]">
                <span>OVERALL SPRINT PROGRESS</span>
                <span className="font-bold text-[#024d37]">{activeProject?.progress}%</span>
              </div>
              <div className="h-2 w-full rounded-full bg-border overflow-hidden">
                <div 
                  className="h-full bg-[#024d37] transition-all duration-500 rounded-full"
                  style={{ width: `${activeProject?.progress}%` }}
                />
              </div>
              <div className="flex justify-between text-[10px] text-muted-foreground pt-1">
                <span>Target: {activeProject?.deadline}</span>
                <span className="capitalize text-foreground font-semibold">{activeProject?.status.replace("_", " ")}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Navigation Tabs */}
        <div className="flex gap-2 border-b border-border pb-3 font-mono text-xs">
          <button
            onClick={() => setActiveTab("status")}
            className={`flex items-center gap-2 rounded-full px-5 py-2 transition-all ${
              activeTab === "status"
                ? "bg-[#024d37] text-white font-bold shadow-md shadow-[#024d37]/20"
                : "border border-border bg-card text-muted-foreground hover:text-foreground"
            }`}
          >
            <FolderKanban className="h-3.5 w-3.5" />
            <span>Milestone Tracker & Tasks</span>
          </button>

          <button
            onClick={() => setActiveTab("chat")}
            className={`flex items-center gap-2 rounded-full px-5 py-2 transition-all relative ${
              activeTab === "chat"
                ? "bg-[#024d37] text-white font-bold shadow-md shadow-[#024d37]/20"
                : "border border-border bg-card text-muted-foreground hover:text-foreground"
            }`}
          >
            <MessageSquare className="h-3.5 w-3.5" />
            <span>Chat with Tech Lead</span>
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
          </button>

          <button
            onClick={() => setActiveTab("invoices")}
            className={`flex items-center gap-2 rounded-full px-5 py-2 transition-all ${
              activeTab === "invoices"
                ? "bg-[#024d37] text-white font-bold shadow-md shadow-[#024d37]/20"
                : "border border-border bg-card text-muted-foreground hover:text-foreground"
            }`}
          >
            <FileText className="h-3.5 w-3.5" />
            <span>Invoices & Scope SLA</span>
          </button>
        </div>

        {/* TAB 1: MILESTONE TRACKER & ACTIVE SPRINT TASKS */}
        {activeTab === "status" && (
          <div className="space-y-6">
            {/* Visual Timeline Pipeline */}
            <div className="rounded-2xl border border-border bg-card p-6 sm:p-8 space-y-6">
              <div className="flex items-center justify-between border-b border-border pb-3 font-mono text-xs">
                <span className="text-[#024d37] font-semibold">// SPRINT MILESTONE ROADMAP</span>
                <span className="text-muted-foreground">LEAD: {activeProject?.lead_developer}</span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 font-mono text-xs">
                <div className="rounded-xl border border-[#024d37] bg-[#024d37]/10 p-4 space-y-2">
                  <div className="flex items-center justify-between text-[#024d37]">
                    <span className="font-bold">01. Architecture Specs</span>
                    <CheckCircle2 className="h-4 w-4" />
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    Requirement mapping, database schemas, and Figma interactive UI sign-off.
                  </p>
                  <span className="inline-block text-[10px] text-[#024d37] font-bold">COMPLETED</span>
                </div>

                <div className="rounded-xl border border-[#024d37] bg-[#024d37]/10 p-4 space-y-2">
                  <div className="flex items-center justify-between text-[#024d37]">
                    <span className="font-bold">02. Core Engineering</span>
                    <CheckCircle2 className="h-4 w-4" />
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    Next.js edge runtime, Supabase PostgreSQL, offline SQLite cache & Electron packaging.
                  </p>
                  <span className="inline-block text-[10px] text-[#024d37] font-bold">COMPLETED</span>
                </div>

                <div className="rounded-xl border border-[#024d37] bg-muted p-4 space-y-2 shadow-sm">
                  <div className="flex items-center justify-between text-foreground">
                    <span className="font-bold text-[#024d37]">03. QA & Hardware Testing</span>
                    <Clock className="h-4 w-4 text-[#024d37] animate-spin" />
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    ESC/POS thermal printer tests, FBR digital invoice signing, and stress load benchmarks.
                  </p>
                  <span className="inline-block text-[10px] text-[#024d37] font-bold">IN PROGRESS (ACTIVE)</span>
                </div>

                <div className="rounded-xl border border-border bg-card p-4 space-y-2 opacity-70">
                  <div className="flex items-center justify-between text-muted-foreground">
                    <span className="font-bold">04. Production Launch</span>
                    <ShieldCheck className="h-4 w-4" />
                  </div>
                  <p className="text-[11px] text-muted-foreground">
                    Final branch rollout, staff operational training, and 90-day SLA warranty kick-off.
                  </p>
                  <span className="inline-block text-[10px] text-muted-foreground">UPCOMING</span>
                </div>
              </div>
            </div>

            {/* Active Sprint Tasks Table */}
            <div className="rounded-2xl border border-border bg-card p-6 sm:p-8 space-y-4">
              <div className="flex items-center justify-between font-mono text-xs">
                <span className="text-[#024d37] font-semibold">
                  // CURRENT SPRINT TASK BOARD ({projectTasks.length} ITEMS)
                </span>
                <span className="text-muted-foreground">Updated in Real-Time</span>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs font-mono">
                  <thead className="border-b border-border bg-muted text-[10px] text-muted-foreground uppercase">
                    <tr>
                      <th className="p-3">Deliverable Item</th>
                      <th className="p-3">Assigned Pod Lead</th>
                      <th className="p-3">Priority</th>
                      <th className="p-3">Target Date</th>
                      <th className="p-3 text-right">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {projectTasks.map((task) => (
                      <tr key={task.id} className="hover:bg-muted/40 transition-colors">
                        <td className="p-3 font-sans font-semibold text-foreground">{task.title}</td>
                        <td className="p-3 text-muted-foreground">{task.assignee_name || "Engineering Team"}</td>
                        <td className="p-3">
                          <span className={`rounded px-2 py-0.5 text-[9px] uppercase font-bold ${
                            task.priority === "urgent" ? "bg-red-500/20 text-red-500" : "bg-muted text-foreground"
                          }`}>
                            {task.priority}
                          </span>
                        </td>
                        <td className="p-3 text-muted-foreground">{task.due_date}</td>
                        <td className="p-3 text-right">
                          <span className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] uppercase font-bold ${
                            task.status === "completed"
                              ? "bg-[#024d37]/20 text-[#024d37] border border-[#024d37]/40"
                              : task.status === "in_progress"
                              ? "bg-amber-500/20 text-amber-600 dark:text-amber-400 border border-amber-500/30"
                              : "bg-muted text-muted-foreground"
                          }`}>
                            {task.status === "completed" && <Check className="h-3 w-3" />}
                            {task.status.replace("_", " ")}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* TAB 2: REAL-TIME TWO-WAY CHAT WITH TECH LEAD */}
        {activeTab === "chat" && (
          <div className="rounded-2xl border border-border bg-card p-6 sm:p-8 space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-border pb-4 font-mono text-xs">
              <div className="flex items-center gap-3">
                <div className="h-9 w-9 rounded-full bg-[#024d37] text-white font-bold flex items-center justify-center text-sm font-sans">
                  MI
                </div>
                <div>
                  <div className="font-bold text-foreground font-sans">Muhammad Irfan (CTO & Lead Architect)</div>
                  <div className="text-[10px] text-[#024d37] flex items-center gap-1">
                    <span className="h-1.5 w-1.5 rounded-full bg-[#024d37] animate-pulse" />
                    ONLINE & READY TO ASSIST
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <a
                  href="https://wa.me/923357758256"
                  target="_blank"
                  rel="noreferrer"
                  className="rounded-full border border-border bg-muted px-3 py-1.5 text-xs text-foreground hover:border-[#024d37] transition-colors flex items-center gap-1.5"
                >
                  <Phone className="h-3.5 w-3.5 text-[#024d37]" /> WhatsApp Direct
                </a>
              </div>
            </div>

            {/* Quick Action Prompt Chips */}
            <div className="flex flex-wrap gap-2 font-mono text-xs">
              <span className="text-[10px] text-muted-foreground self-center mr-1">QUICK INQUIRIES:</span>
              <button
                onClick={() => handleQuickPrompt("Can you provide the latest staging preview URL for our team to test?")}
                className="rounded-full border border-border bg-muted px-3 py-1 text-[11px] text-foreground hover:border-[#024d37] hover:bg-[#024d37]/10 transition-colors"
              >
                + Request Staging Link
              </button>
              <button
                onClick={() => handleQuickPrompt("Could we schedule a 15-min Zoom call to review hardware printer drivers?")}
                className="rounded-full border border-border bg-muted px-3 py-1 text-[11px] text-foreground hover:border-[#024d37] hover:bg-[#024d37]/10 transition-colors"
              >
                + Schedule Architecture Call
              </button>
              <button
                onClick={() => handleQuickPrompt("We have an additional feature request for batch expiry notifications.")}
                className="rounded-full border border-border bg-muted px-3 py-1 text-[11px] text-foreground hover:border-[#024d37] hover:bg-[#024d37]/10 transition-colors"
              >
                + Submit Scope Addon
              </button>
            </div>

            {/* Messages Thread Container */}
            <div className="min-h-[340px] max-h-[480px] overflow-y-auto rounded-xl border border-border bg-muted/40 p-4 space-y-4 font-mono text-xs">
              {relevantChat.map((msg) => {
                const isMe = msg.sender_id === currentUser?.id;
                return (
                  <div
                    key={msg.id}
                    className={`flex flex-col ${isMe ? "items-end" : "items-start"}`}
                  >
                    <div className="flex items-center gap-2 mb-1 text-[10px] text-muted-foreground">
                      <span>{msg.sender_name}</span>
                      <span>•</span>
                      <span>{msg.timestamp}</span>
                    </div>

                    <div
                      className={`max-w-md rounded-2xl p-4 font-sans text-xs sm:text-sm leading-relaxed shadow-sm ${
                        isMe
                          ? "bg-[#024d37] text-white rounded-tr-none"
                          : "bg-card border border-border text-foreground rounded-tl-none"
                      }`}
                    >
                      {msg.text}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Message Input Box */}
            <form onSubmit={handleSendMessage} className="flex gap-2">
              <input
                type="text"
                placeholder="Type your message to Muhammad Irfan (CTO)..."
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                className="flex-1 rounded-xl border border-border bg-muted px-4 py-3 text-xs sm:text-sm text-foreground focus:border-[#024d37] focus:outline-none font-sans"
              />
              <button
                type="submit"
                disabled={!chatInput.trim()}
                className="inline-flex items-center gap-2 rounded-xl bg-[#024d37] px-6 py-3 font-mono text-xs font-bold uppercase tracking-wider text-white hover:bg-[#036549] transition-all disabled:opacity-50"
              >
                <Send className="h-3.5 w-3.5" />
                <span>Send</span>
              </button>
            </form>
          </div>
        )}

        {/* TAB 3: INVOICES & SCOPE SLA */}
        {activeTab === "invoices" && (
          <div className="rounded-2xl border border-border bg-card p-6 sm:p-8 space-y-6">
            <div className="flex items-center justify-between border-b border-border pb-3 font-mono text-xs">
              <span className="text-[#024d37] font-semibold">// FINANCIAL LEDGER & CONTRACT MILESTONES</span>
              <span className="text-muted-foreground">TOTAL: {activeProject?.budget}</span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 font-mono text-xs">
              <div className="rounded-xl border border-[#024d37]/40 bg-[#024d37]/10 p-5 space-y-2">
                <span className="text-[10px] text-[#024d37] font-bold">MILESTONE 01: ADVANCE DEPOSIT</span>
                <div className="text-xl font-bold text-foreground font-sans">PKR 150,000</div>
                <div className="text-[10px] text-[#024d37] flex items-center gap-1 font-bold">
                  <CheckCircle2 className="h-3.5 w-3.5" /> PAID & RECEIPT ISSUED
                </div>
              </div>

              <div className="rounded-xl border border-border bg-muted p-5 space-y-2">
                <span className="text-[10px] text-muted-foreground font-bold">MILESTONE 02: STAGING BUILD</span>
                <div className="text-xl font-bold text-foreground font-sans">PKR 150,000</div>
                <div className="text-[10px] text-amber-500 font-bold">
                  ● PENDING STAGING SIGN-OFF
                </div>
              </div>

              <div className="rounded-xl border border-border bg-muted p-5 space-y-2">
                <span className="text-[10px] text-muted-foreground font-bold">MILESTONE 03: DEPLOYMENT & SLA</span>
                <div className="text-xl font-bold text-foreground font-sans">PKR 150,000</div>
                <div className="text-[10px] text-muted-foreground font-bold">
                  ○ DUE UPON PRODUCTION LAUNCH
                </div>
              </div>
            </div>

            <div className="rounded-xl border border-border bg-muted/60 p-6 space-y-3 font-mono text-xs">
              <div className="font-bold text-foreground">// LEGAL SLA & SOURCE CODE WARRANTY:</div>
              <ul className="space-y-1.5 text-muted-foreground leading-relaxed">
                <li>• <strong>IP Ownership:</strong> 100% complete source code ownership transferred upon final deployment.</li>
                <li>• <strong>Warranty SLA:</strong> {activeProject?.sla_warranty || "90 Days complimentary technical support & bug warranty."}</li>
                <li>• <strong>Hosting & Cloud:</strong> Managed PostgreSQL and edge server uptime guaranteed at 99.95%.</li>
              </ul>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
