"use client";

import React, { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { StatCard } from "@/components/dashboard/stats";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Send,
  Mail,
  Phone,
  Search,
  Filter,
  Eye,
  MousePointer,
  MessageSquare,
} from "lucide-react";
import { useApiData } from "@/hooks/use-api-data";
import { mockOutreach } from "@/lib/mock-data";
import { formatRelativeTime, getStatusColor } from "@/lib/utils";
import type { Outreach } from "@/types";

export default function OutreachPage() {
  const [filterChannel, setFilterChannel] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");
  const [searchTerm, setSearchTerm] = useState("");

  const { data: apiOutreach } = useApiData<Outreach[]>('/api/outreach', []);
  const allOutreach = apiOutreach.length > 0 ? apiOutreach : mockOutreach;

  const totalSent = allOutreach.filter((o) => o.sent_at).length;
  const totalOpened = allOutreach.filter((o) => o.opened_at).length;
  const totalClicked = allOutreach.filter((o) => o.clicked_at).length;
  const totalReplied = allOutreach.filter((o) => o.replied_at).length;
  const openRate = totalSent > 0 ? Math.round((totalOpened / totalSent) * 100) : 0;
  const replyRate = totalSent > 0 ? Math.round((totalReplied / totalSent) * 100) : 0;

  const filteredOutreach = allOutreach.filter((item) => {
    const matchesSearch =
      (item.subject || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
      (item.match?.buyer?.name || "").toLowerCase().includes(searchTerm.toLowerCase());
    const matchesChannel = filterChannel === "all" || item.channel === filterChannel;
    const matchesStatus = filterStatus === "all" || item.status === filterStatus;
    return matchesSearch && matchesChannel && matchesStatus;
  });

  const emailOutreach = filteredOutreach.filter((o) => o.channel === "email");
  const smsOutreach = filteredOutreach.filter((o) => o.channel === "sms");

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-navy-900">Outreach Center</h1>
        <p className="text-sm text-navy-500 mt-1">
          Track all email and SMS communications with buyers
        </p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
        <StatCard
          title="Total Sent"
          value={totalSent}
          icon={Send}
          iconColor="text-blue-600"
        />
        <StatCard
          title="Open Rate"
          value={`${openRate}%`}
          change={`${totalOpened} opened`}
          changeType="neutral"
          icon={Eye}
          iconColor="text-indigo-600"
        />
        <StatCard
          title="Click Rate"
          value={`${totalSent > 0 ? Math.round((totalClicked / totalSent) * 100) : 0}%`}
          change={`${totalClicked} clicked`}
          changeType="neutral"
          icon={MousePointer}
          iconColor="text-purple-600"
        />
        <StatCard
          title="Reply Rate"
          value={`${replyRate}%`}
          change={`${totalReplied} replied`}
          changeType="positive"
          icon={MessageSquare}
          iconColor="text-emerald-600"
        />
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-navy-400" />
          <Input
            placeholder="Search by subject or buyer..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterChannel} onValueChange={setFilterChannel}>
          <SelectTrigger className="w-full sm:w-36">
            <SelectValue placeholder="Channel" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Channels</SelectItem>
            <SelectItem value="email">Email</SelectItem>
            <SelectItem value="sms">SMS</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-full sm:w-40">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="sent">Sent</SelectItem>
            <SelectItem value="delivered">Delivered</SelectItem>
            <SelectItem value="opened">Opened</SelectItem>
            <SelectItem value="clicked">Clicked</SelectItem>
            <SelectItem value="replied">Replied</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Outreach Tabs */}
      <Tabs defaultValue="all" className="space-y-4">
        <TabsList>
          <TabsTrigger value="all">All ({filteredOutreach.length})</TabsTrigger>
          <TabsTrigger value="email">Email ({emailOutreach.length})</TabsTrigger>
          <TabsTrigger value="sms">SMS ({smsOutreach.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="all">
          <OutreachTable items={filteredOutreach} />
        </TabsContent>
        <TabsContent value="email">
          <OutreachTable items={emailOutreach} />
        </TabsContent>
        <TabsContent value="sms">
          <OutreachTable items={smsOutreach} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

function OutreachTable({ items }: { items: Outreach[] }) {
  return (
    <Card>
      <CardContent className="p-0">
        <div className="overflow-x-auto -mx-px">
          <table className="w-full min-w-[700px]">
            <thead>
              <tr className="border-b border-navy-100">
                <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                  Channel
                </th>
                <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                  Recipient
                </th>
                <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                  Subject / Message
                </th>
                <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                  Status
                </th>
                <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                  Timeline
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-navy-50">
              {items.map((item) => (
                <tr key={item.id} className="hover:bg-navy-25 transition-colors">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      {item.channel === "email" ? (
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-blue-50">
                          <Mail className="h-4 w-4 text-blue-600" />
                        </div>
                      ) : (
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-green-50">
                          <Phone className="h-4 w-4 text-green-600" />
                        </div>
                      )}
                      <span className="text-xs text-navy-500 capitalize">{item.channel}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <p className="text-sm font-medium text-navy-900">
                      {item.match?.buyer?.name || "Unknown"}
                    </p>
                    <p className="text-xs text-navy-500">
                      {item.match?.buyer?.company || ""}
                    </p>
                  </td>
                  <td className="px-6 py-4">
                    <p className="text-sm text-navy-700 truncate max-w-xs">
                      {item.subject || item.body.slice(0, 60) + "..."}
                    </p>
                  </td>
                  <td className="px-6 py-4">
                    <Badge className={getStatusColor(item.status)} variant="secondary">
                      {item.status}
                    </Badge>
                  </td>
                  <td className="px-6 py-4">
                    <div className="space-y-0.5 text-xs">
                      {item.sent_at && (
                        <p className="text-navy-500">
                          Sent {formatRelativeTime(item.sent_at)}
                        </p>
                      )}
                      {item.opened_at && (
                        <p className="text-indigo-600">
                          Opened {formatRelativeTime(item.opened_at)}
                        </p>
                      )}
                      {item.replied_at && (
                        <p className="text-emerald-600">
                          Replied {formatRelativeTime(item.replied_at)}
                        </p>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {items.length === 0 && (
          <div className="text-center py-12">
            <Send className="h-12 w-12 text-navy-300 mx-auto mb-4" />
            <p className="text-sm text-navy-500">No outreach found.</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
